You are given a binary tree encoded as a single space-separated level-order array. Values are read top-to-bottom, left-to-right. The literal token null marks a missing child, so a null never has children of its own. An empty tree is encoded as the single token null.
The depth of the tree is the number of nodes on the longest path from the root down to any leaf. An empty tree has depth 0; a tree with only a root has depth 1.
Print that maximum depth.
A single line containing the level-order tokens separated by single spaces. Each token is either an integer or the literal null. The line may also be exactly null for an empty tree.
A single integer: the maximum depth in nodes.
null token ever has children listed after it).Balanced tree
Input
3 9 20 null null 15 7
Expected
3
Explanation
Root 3 has children 9 and 20; 20 has children 15 and 7. The longest root-to-leaf path passes through 3 -> 20 -> 15 (or 3 -> 20 -> 7), which is 3 nodes, so the depth is 3.
Left-leaning chain
Input
1 2 null 3 null 4
Expected
4
Explanation
The tree is a straight chain 1 -> 2 -> 3 -> 4 down the left/first-child side, so the maximum depth is 4 nodes.
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 →