
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]
- 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]
- 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
Editorial
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. |
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