Java program to find the maximum depth or height of a tree
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.
In the above binary tree,
- 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.
- When a node is created, data will pass to data attribute of the node and both left and right will be set to null.
- Define another class which has an attribute root.
- Root represents the root node of the tree and initializes it to null.
a. findHeight() will determine the maximum height of the binary tree:
- It checks whether the root is null, which means the tree is empty.
- If the tree is not empty, traverse through left subtree to determine the height of the left subtree and store the value in leftHeight.
- Similarly, determine the height of the right subtree and store the value in rightHeight.
- Maximum will determine the maximum of leftHeight and rightHeight then, add 1 for root's height.
Maximum height of given binary tree: 5