-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrees2.py
More file actions
55 lines (42 loc) · 1.28 KB
/
Copy pathTrees2.py
File metadata and controls
55 lines (42 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Treenode:
def __init__(self,data):
self.data = data
self.children = []
self.parent = None
def add_child(self,child):
child.parent = self
self.children.append(child)
def get_level(self):
level = 0
p = self.parent
while p:
level += 1
p = p.parent
return level
def print_tree(self):
spaces = " "*self.get_level()*3
prefix = spaces+"|__"
print(prefix + self.data)
if self.children:
for child in self.children:
child.print_tree()
def build_product_tree():
root = Treenode("Electronics")
laptop = Treenode("Laptop")
laptop.add_child(Treenode("MAC"))
laptop.add_child(Treenode("Windows"))
laptop.add_child(Treenode("Linux"))
TV = Treenode("TV")
TV.add_child(Treenode("Samsung"))
TV.add_child(Treenode("Toshiba"))
TV.add_child(Treenode("Sony"))
Refrigeretor = Treenode("Refrigeretor")
Refrigeretor.add_child(Treenode("Haier"))
Refrigeretor.add_child(Treenode("Samsung"))
Refrigeretor.add_child(Treenode("LG"))
root.add_child(laptop)
root.add_child(TV)
root.add_child(Refrigeretor)
return root
root = build_product_tree()
root.print_tree()