0% found this document useful (0 votes)
21 views2 pages

2

The document describes a recursive algorithm to compute the height of a tree. It starts by selecting a root node and recursively traversing down to the deepest level, tracking the maximum depth at each node. It then traverses back up to the root while incrementing the height at each node by 1 plus the maximum height of its children. The algorithm has O(n) time and space complexity, where n is the number of nodes, as it traverses the tree only once.

Uploaded by

Sagar Chaglani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views2 pages

2

The document describes a recursive algorithm to compute the height of a tree. It starts by selecting a root node and recursively traversing down to the deepest level, tracking the maximum depth at each node. It then traverses back up to the root while incrementing the height at each node by 1 plus the maximum height of its children. The algorithm has O(n) time and space complexity, where n is the number of nodes, as it traverses the tree only once.

Uploaded by

Sagar Chaglani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Ans 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:

def __init__(self, index):

self.index = index

self.children = []

def compute_height(root):

if not root.children:

return 1

else:

heights = []

for child in root.children:

heights.append(compute_height(child))

return 1 + max(heights)

n = int(input())

parent = list(map(int, input().split()))

# 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).

You might also like