Height of a binary tree
Standard · Write code · about 8 min
Given the root of a binary tree, return its height: the number of edges on the longest path from the root down to a leaf. A single node has height 0 and an empty tree has height -1.
Example 1
Input:
[[1,2,3,4,5,null,6,null,null,7]]
Output:
3
The longest path 1, 2, 5, 7 has 3 edges.
Example 2
Input:
[[3,9,20,null,null,15,7]]
Output:
2
Constraints
- 0 ≤ number of nodes ≤ 1,000
- -1,000 ≤ Node.val ≤ 1,000
- The tree is given in level order; null marks a missing child
Learn the idea first: Trees: root, leaf, depth, height, subtree, a visual lesson.
More Trees: root, leaf, depth, height, subtree problems
- Label the parts of a tree Warm-up
- Compute the height Warm-up
- Count the leaves Standard
- Count the leaves in code Standard
- Count the nodes at depth d Standard
- Nodes at depth d in a full tree Challenge