-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree.py
54 lines (40 loc) · 1.05 KB
/
tree.py
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
53
54
class tree_node:
def __init__(self, data):
self.data = data
self.children = []
self.parent = None
def add_child(self, child):
self.parent = self
self.children.append(child)
def tree_height(self):
count = 0
p = self.parent
while p:
count += 1
p = p.parent
print(self.parent)
return count
def print_tree(self):
# print(self.tree_height()*" " + self.data)
print(self.tree_height())
if self.children:
for child in self.children:
child.print_tree()
if __name__ == "__main__":
root = tree_node("Electronics")
TV = tree_node("Television")
laptop = tree_node("Laptop")
cellphone = tree_node("Cellphone")
root.print_tree()
root.add_child(TV)
root.add_child(laptop)
root.add_child(cellphone)
TV.add_child(tree_node("Samsung"))
TV.add_child(tree_node("Sony"))
TV.add_child(tree_node("LG"))
laptop.add_child(tree_node("Windows"))
laptop.add_child(tree_node("Mac"))
cellphone.add_child(tree_node("Apple"))
cellphone.add_child(tree_node("Vivo"))
cellphone.add_child(tree_node("MI"))
# root.print_tree()