Problem 141
Maximum Depth of Binary Tree
Easy · 10 pts · Tree, Depth-First Search, Binary Tree
Problem
You are given a binary tree. Print its maximum depth: the number of nodes on the longest path from the root down to a leaf (a node with no children). A tree with only a root has depth 1, and an empty tree has depth 0. The depth of a tree is 1 plus the larger of the depths of its left and right subtrees, which gives a short recursive solution. A level-by-level breadth-first search that counts the levels works as well.
Input
First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child (the same format LeetCode uses).
Output
Print the maximum depth.
Constraints
0 <= number of nodes <= 10000; -100 <= value <= 100
Example input
7 3 9 20 null null 15 7
Example output
3
Explanation
The tree has root 3 with children 9 and 20, and 20 has children 15 and 7. The longest root-to-leaf paths, such as 3 → 20 → 15, contain 3 nodes, so the depth is 3.