Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions 2. Data Structures/2_tree_height.py/tree_height.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# python3

import sys
import threading
import collections

def compute_height(n, parents):
# Replace this code with a faster implementation
max_height = -1
tree = collections.defaultdict(list)
q = collections.deque([-1])
for i, node in enumerate(parents):
tree[node].append(i)
while q:
max_height += 1
l = len(q)
for _ in range(l):
node = q.popleft()
q.extend(tree[node])
return max_height

def main():
n = int(input())
parents = list(map(int, input().split()))
print(compute_height(n, parents))


# In Python, the default limit on recursion depth is rather low,
# so raise it here for this problem. Note that to take advantage
# of bigger stack, we have to launch the computation in a new thread.
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
threading.Thread(target=main).start()