2
2
To compute the height of a given tree, we can use the recursive method. We can start by selecting any
node as the root node of the tree and traverse down to the deepest level of the tree by making recursive
calls. Once we reach the deepest level, we can start going back up towards the root and keep track of the
maximum depth at each node.We can implement this algorithm by starting from the root node and
recursively computing the height of the subtrees of each child node. We can then take the maximum of
these heights and add 1 to it to get the height of the current node. We can continue this process until we
reach the root node.Here's the Python code to implement the above approach:
class Node:
self.index = index
self.children = []
def compute_height(root):
if not root.children:
return 1
else:
heights = []
heights.append(compute_height(child))
return 1 + max(heights)
n = int(input())
# create nodes
nodes = []
for i in range(n):
nodes.append(Node(i))
# build tree
for i in range(n):
if parent[i] == -1:
root = nodes[i]
else:
nodes[parent[i]].children.append(nodes[i])
print(compute_height(root))
.
The above code has a time complexity of O(n), where n is the number of nodes in the tree. Since we traverse the tree only once,
the space complexity is also O(n).