Depth of a Binary Tree
You are given root, the root of a binary tree.
Return the depth of the tree: the number of nodes on the longest path that starts at the root and goes down to a leaf. A leaf is a node with no children.
A tree with only a root has depth 1. An empty tree has depth 0.
How the input is shown
A tree is shown as a list in level order: the root first, then each level from left to right. null marks a missing child, and missing children of a missing node are not listed. For example, [4, 2, 7, null, 3] is root 4 with left child 2 and right child 7, and 2 has only a right child, 3. An empty tree is [].
Note
- Hint: the depth of a node is 1 plus the larger of the depths of its two subtrees, and the depth of a missing node is 0. You can also visit the tree level by level with a queue and count the levels.
Examples
Example 1
- Input:
- [6,2,9,null,4,null,null,3]
- Output:
- 4
The longest path is 6 -> 2 -> 4 -> 3. It has 4 nodes. The path 6 -> 9 has only 2.
Example 2
- Input:
- [1,null,2,null,3]
- Output:
- 3
Every node has only a right child: 1 -> 2 -> 3. That is 3 nodes deep.
Example 3
- Input:
- []
- Output:
- 0
The tree is empty, so its depth is 0.
Constraints
0 <=number of nodes<= 60-100 <= Node.val <= 100
Run checks your code against the 3 examples. Submit checks it against all 123 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.