1+
2+ class NodeTree :
3+ def __init__ (self , data ):
4+ self .data = data
5+ self .children = []
6+ self .parent = None
7+
8+ def add_node (self , node ):
9+ self .children .append (node )
10+ node .parent = self
11+
12+ def print_tree (self ):
13+
14+ space = "\t "
15+ print (space * self .get_level (), self .data )
16+ for child in self .children :
17+ child .print_tree ()
18+
19+ def get_level (self ):
20+ p = self .parent
21+ lvl = 1
22+ while p :
23+ lvl += 1
24+ p = p .parent
25+ return lvl
26+
27+
28+ if __name__ == "__main__" :
29+
30+ # Create a Node (root)
31+ root = NodeTree ("Electronics" )
32+
33+ # Create Children for root
34+ ## first child
35+ laptop = NodeTree ("Laptop" )
36+ laptop .add_node (NodeTree ("Acer" ))
37+ laptop .add_node (NodeTree ("Asus" ))
38+ laptop .add_node (NodeTree ("Mac" ))
39+
40+ root .add_node (laptop )
41+
42+ ## second child
43+ phone = NodeTree ("Phone" )
44+ phone .add_node (NodeTree ("iPhone" ))
45+ phone .add_node (NodeTree ("Samsung" ))
46+ phone .add_node (NodeTree ("Xiaomi" ))
47+
48+ root .add_node (phone )
49+
50+ ## third child
51+ tv = NodeTree ("TV" )
52+ tv .add_node (NodeTree ("Goldiran" ))
53+ tv .add_node (NodeTree ("LG" ))
54+ tv .add_node (NodeTree ("SONY" ))
55+
56+ root .add_node (tv )
57+
58+ root .print_tree ()
59+
60+ # print(root.get_level())
61+ # print(root.children[0].get_level())
62+ # print(root.children[0].children[0].get_level())
63+
64+
65+ # print("\n")
66+ # print(root.data)
67+ # print("\t" + root.children[0].data)
68+ # print("\t\t" + root.children[0].children[0].data)
69+ # print("\t\t" + root.children[0].children[1].data)
70+ # print("\t\t" + root.children[0].children[2].data)
71+
72+ # print("\t" + root.children[1].data)
73+ # print("\t\t" + root.children[1].children[0].data)
74+ # print("\t\t" + root.children[1].children[1].data)
75+ # print("\t\t" + root.children[1].children[2].data)
76+
77+ # print("\t" + root.children[2].data)
78+ # print("\t\t" + root.children[2].children[0].data)
79+ # print("\t\t" + root.children[2].children[1].data)
80+ # print("\t\t" + root.children[2].children[2].data)
0 commit comments