Amazing-Python-Scripts
98 строк · 3.5 Кб
1"""
2GENERAL TREE
3Data is stored in hierarchical form
4
5ROOT --- Level 0
6____________________|____________________
7A B C --- Level 1
8_____|_____ _____|_____ _____|_____
9| | | | | | | | |
10D E F G H I J K L --- Level 2
11_____|_____ _____|_____
12| | | | | |
13M N O P Q R --- Level 3
14
15
16
17
18Here, ROOT is "ROOT NODE" and A, B, C are "CHILD NODE"
19> B-D-F-G is a sub-tree
20> B is 'ROOT NODE' for F, G, H and G is 'ROOT NODE' for Q, R
21> Those nodes [E, F, H, I, J, K, L...] who do not have any child node are "LEAF NODE"
22> For (D, E), A will be Ancestor and for A, (D, E) would be Descendants
23Tree is a recursive dta structure where a child node is another tree in itself
24
25"""
26
27
28class TreeNode:
29""" Class TreeNode """
30
31def __init__(self, data):
32self.data = data
33self.children = []
34self.parent = None
35
36def add_child(self, child):
37""" Adds children elements to Tree """
38child.parent = self # child is an instance of class(node)
39# adding a child node to tree
40self.children.append(child)
41
42def get_level(self):
43""" Gets the level of Tree by counting ancestors: if a node has no ancestor, it is root node """
44level = 0 # initialised level to 0
45p = self.parent
46while p:
47"""keep on going through parents and increasing levels"""
48level += 1 # increase level by 1
49p = p.parent
50return level
51
52def print_tree(self):
53"""Display Tree in hierarchical format"""
54spaces = ' ' * self.get_level() * 3 # printing 3 spaces for each level
55prefix = spaces + "|__" if self.parent else ""
56# prints prefix(probably spaces) based on level
57print(prefix + self.data)
58
59# At leaf nodes, self.children will be an empty array... so we create a check if self.children() is an empty array or not
60if self.children: # checks if len(self.children > 0)
61for child in self.children:
62child.print_tree() # It will recursively call this fn and print the sub-trees
63
64
65def electronic_product():
66root = TreeNode("Electronics")
67
68laptop = TreeNode("Laptop")
69laptop.add_child(TreeNode("Mac"))
70laptop.add_child(TreeNode("Surface"))
71laptop.add_child(TreeNode("Thinkpad"))
72
73cellphones = TreeNode("cell Phone")
74cellphones.add_child(TreeNode("iphone"))
75cellphones.add_child(TreeNode("Samsung"))
76cellphones.add_child(TreeNode("Vivo"))
77
78tv = TreeNode("TV")
79tv.add_child(TreeNode("Samsung"))
80tv.add_child(TreeNode("MI"))
81
82root.add_child(laptop)
83root.add_child(cellphones)
84root.add_child(tv)
85
86# print(laptop.get_level()) # 1
87# print(cellphones.get_level()) # 1
88# print(tv.get_level()) # 1
89
90return root
91
92
93# main method
94if __name__ == '__main__':
95root = electronic_product()
96root.print_tree() # prints tree in hierarchical format
97
98# print(root.get_level()) # 0 // get level of root node
99