Count the leaves in code
Standard · Write code · about 7 min
Given the root of a binary tree, return the number of leaves: nodes with no left child and no right child.
Example 1
Input:
[[1,2,3,4,5,null,6,null,null,7]]
Output:
3
The leaves are 4, 7 and 6.
Example 2
Input:
[[3,9,20,null,null,15,7]]
Output:
3
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
- Height of a binary tree Standard
- Count the nodes at depth d Standard
- Nodes at depth d in a full tree Challenge