A leaf is a node that has no left child and no right child. Count how many leaves the given binary tree has.
One line: the binary tree as a level-order array.
The tree is encoded on ONE line as a space-separated level-order (breadth-first) array. The token null marks a missing child; the children of a null are omitted from the array. An empty tree is written as the single token null.
A single integer: the number of leaf nodes (0 for an empty tree).
Example 1
Input
1 2 3 4 5 null 6
Expected
3
Explanation
Nodes 4, 5 and 6 have no children, so there are 3 leaves.
Example 2
Input
42
Expected
1
Explanation
A single root node is itself a leaf, so the answer is 1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →