Loading problem...
Given the root node of a binary tree, calculate and return the height of the tree.
The height of a binary tree is defined as the number of nodes along the longest path from the root node down to the deepest leaf node. This measurement represents the maximum number of levels in the tree structure.
A leaf node is a node that has no children (both left and right child pointers are null).
If the tree is empty (root is null), the height should be 0.
root = [3,9,20,null,null,15,7]3The tree has the following structure:
3
/
9 20
/
15 7
The longest path from root to a leaf is either 3 → 20 → 15 or 3 → 20 → 7, both containing 3 nodes. Therefore, the height is 3.
root = [1,null,2]2The tree has the following structure: 1
2
The only path from root to leaf is 1 → 2, containing 2 nodes. Therefore, the height is 2.
root = [1,2,3,4,5,6,7]3This is a complete binary tree with 7 nodes: 1 / 2 3 / \ / 4 5 6 7
All leaf nodes (4, 5, 6, 7) are at the same level. The longest path has 3 nodes.
Constraints