Tutorialspoint
Problem
Solution
Submissions

Height of Binary Tree

Certification: Basic Level Accuracy: 100% Submissions: 1 Points: 8

Write a Java program to find the height of a binary tree. The height of a binary tree is the number of edges in the longest path from the root node to any leaf node.

Example 1
  • Input: Binary tree [3,9,20,null,null,15,7]

    Height of Binary Tree with Null Edges

  • Output: 2
  • Explanation: The longest path from root to leaf is 3->20->7, which has 2 edges.
Example 2
  • Input: Binary tree [1,2,3,4,5]

    Height of Binary Tree with Proper Edges

  • Output: 2
  • Explanation: The longest paths from root to leaf are 1->2->4 and 1->2->5, both with 2 edges.
Constraints
  • 0 ≤ Number of nodes ≤ 1000
  • -1000 ≤ Node.val ≤ 1000
  • Time Complexity: O(n) where n is the number of nodes
  • Space Complexity: O(h) where h is the height of the tree
Binary TreeCapgeminiZomato
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a recursive approach to calculate the height
  • The height of an empty tree is -1 (or some implementations use 0)
  • The height of a leaf node is 0
  • For non-leaf nodes, compute the height of left and right subtrees
  • The height of a node is 1 + maximum of the heights of its left and right subtrees

Steps to solve by this approach:

 Step 1: Check if the root is null. If it is, return -1 (height of empty tree).
 Step 2: Recursively calculate the height of the left subtree.
 Step 3: Recursively calculate the height of the right subtree.
 Step 4: Find the maximum of left and right subtree heights.
 Step 5: Return 1 plus the maximum height (adding 1 for the current edge).
 Step 6: The recursive calls will propagate heights up from leaf nodes to the root.
 Step 7: The final result represents the longest path from root to any leaf.

Submitted Code :