Home » Program to Find the Maximum Depth or Height of a Tree

Program to Find the Maximum Depth or Height of a Tree

by Online Tutorials Library

Q. Program to find the maximum depth or height of a tree

Explanation

In this program, we need to find out the maximum height of the binary tree. The height of the binary tree can be defined as the number of nodes between root and a leaf. Maximum height will be the number of levels between root and deepest leaf. To solve this problem, we traverse through the left subtree and calculate the height of the left subtree. Again, calculate the height of the right subtree by traversing through it. Maximum height will be maximum of the height of the left subtree and right subtree.

Program to find the maximum depth or height of a tree

In the above binary tree,

Height of left subtree is 2.
Height of right subtree is 4.
MaxHeight = Max(leftHeight, rightHeight) + 1; Here, 1 Represents root node’s height

The maximum height of the given binary tree is (4 + 1) = 5 denoted by white dotted line.

Algorithm

  1. Define Node class which has three attributes namely: data left and right. Here, left represents the left child of the node and right represents the right child of the node.
  2. When a node is created, data will pass to data attribute of the node and both left and right will be set to null.
  3. Define another class which has an attribute root.
    1. Root represents the root node of the tree and initializes it to null.
  4. findHeight() will determine the maximum height of the binary tree:
    1. It checks whether the root is null, which means the tree is empty.
    2. If the tree is not empty, traverse through left subtree to determine the height of the left subtree and store the value in leftHeight.
    3. Similarly, determine the height of the right subtree and store the value in rightHeight.
    4. Maximum will determine the maximum of leftHeight and rightHeight then, add 1 for root’s height.

Solution

Python

Output:

Maximum height of given binary tree: 5  

C

Output:

Maximum height of given binary tree: 5  

JAVA

Output:

Maximum height of given binary tree: 5  

C#

Output:

Maximum height of given binary tree: 5  

PHP

Output:

Maximum height of given binary tree: 5  

Next TopicPrograms List

You may also like