Amazing-Python-Scripts

Форк
0
98 строк · 3.5 Кб
1
"""
2
GENERAL TREE
3
    Data is stored in hierarchical form
4

5
                                            ROOT                                            --- Level 0
6
                         ____________________|____________________
7
                         A                   B                   C                          --- Level 1
8
                    _____|_____         _____|_____         _____|_____
9
                    |         |         |    |     |        |   |   |  |
10
                    D         E         F    G     H        I   J   K  L                    --- Level 2
11
               _____|_____              _____|_____
12
               |   |  |  |              |         |
13
               M   N  O   P             Q         R                                         --- Level 3
14

15

16

17

18
         Here, 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
23
    Tree is a recursive dta structure where a child node is another tree in itself
24

25
"""
26

27

28
class TreeNode:
29
    """ Class TreeNode """
30

31
    def __init__(self, data):
32
        self.data = data
33
        self.children = []
34
        self.parent = None
35

36
    def add_child(self, child):
37
        """ Adds children elements to Tree """
38
        child.parent = self  # child is an instance of class(node)
39
        # adding a child node to tree
40
        self.children.append(child)
41

42
    def get_level(self):
43
        """ Gets the level of Tree by counting ancestors: if a node has no ancestor, it is root node """
44
        level = 0  # initialised level to 0
45
        p = self.parent
46
        while p:
47
            """keep on going through parents and increasing levels"""
48
            level += 1  # increase level by 1
49
            p = p.parent
50
        return level
51

52
    def print_tree(self):
53
        """Display Tree in hierarchical format"""
54
        spaces = ' ' * self.get_level() * 3  # printing 3 spaces for each level
55
        prefix = spaces + "|__" if self.parent else ""
56
        # prints prefix(probably spaces) based on level
57
        print(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
60
        if self.children:  # checks if len(self.children > 0)
61
            for child in self.children:
62
                child.print_tree()  # It will recursively call this fn and print the sub-trees
63

64

65
def electronic_product():
66
    root = TreeNode("Electronics")
67

68
    laptop = TreeNode("Laptop")
69
    laptop.add_child(TreeNode("Mac"))
70
    laptop.add_child(TreeNode("Surface"))
71
    laptop.add_child(TreeNode("Thinkpad"))
72

73
    cellphones = TreeNode("cell Phone")
74
    cellphones.add_child(TreeNode("iphone"))
75
    cellphones.add_child(TreeNode("Samsung"))
76
    cellphones.add_child(TreeNode("Vivo"))
77

78
    tv = TreeNode("TV")
79
    tv.add_child(TreeNode("Samsung"))
80
    tv.add_child(TreeNode("MI"))
81

82
    root.add_child(laptop)
83
    root.add_child(cellphones)
84
    root.add_child(tv)
85

86
    # print(laptop.get_level()) # 1
87
    # print(cellphones.get_level()) # 1
88
    # print(tv.get_level()) # 1
89

90
    return root
91

92

93
# main method
94
if __name__ == '__main__':
95
    root = electronic_product()
96
    root.print_tree()  # prints tree in hierarchical format
97

98
    # print(root.get_level()) # 0 // get level of root node
99

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.