summaryrefslogtreecommitdiff
path: root/sources/tree_height.py
blob: 9cebe3a88351d26e353afe8dc6f8c6abaac3c034 (plain)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# Uses python3
import queue


class Node(object):
    def __init__(self, key):
        self._key = key
        self.children = []

    @property
    def key(self):
        return self._key

    @key.setter
    def key(self, key):
        self._key = key

    def add_child(self, child):
        self.children.extend([child])

    def get_children(self):
        return self.children


def tree_level_counter(nodes, root_index):
    level_counter = 1
    q = queue.Queue()
    pop_count = 0
    child_count = len(nodes[root_index].get_children())
    grand_children_count = 0
    for i in range(child_count):
        q.put(nodes[root_index].get_children()[i])
    while not q.empty():
        if pop_count < child_count:
            node = q.get()
            i = len(node.get_children())
            if i != 0:
                for j in range(i):
                    q.put(node.get_children()[j])
            grand_children_count = grand_children_count + i
            pop_count = pop_count + 1
        else:
            pop_count = 0
            child_count = grand_children_count
            grand_children_count = 0
            level_counter = level_counter + 1
    return level_counter + 1


def get_height(a):
    # The code below has the bug of alias/referencing. Code after that fixed it.
    # nodes = [Node(-5)] * len(a)
    nodes = []
    for i in range(len(a)):
        nodes.append(Node(i))
    root_index = 0

    for i in range(len(a)):
        parent_index = a[i]
        nodes[i].key = i
        if parent_index == -1:
            root_index = i
        else:
            nodes[parent_index].add_child(nodes[i])
    return tree_level_counter(nodes, root_index)


if __name__ == '__main__':
    n = int(input())
    parents = list(map(int, input().split()))
    print(get_height(parents))