Binary Trees Depth first: return a value up
344. Maximum Depth of Binary Tree
You are given root, the root node of a binary tree. Return the maximum depth of the tree.
A binary tree is made of nodes. Each node holds a value and has at most two children, a left child and a right child. A node with no children is a leaf. The maximum depth is the number of nodes on the longest path that starts at the root and goes down to a leaf. An empty tree has depth 0.
The examples write a tree level by level, from left to right, with null where a child is missing. So
root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The
missing children after the last node are left out.
Example 1
Input: root = [7, 3, 12, null, 5, 9, 15, null, null, 1]
4Explanation: The longest path from the root is 7 → 12 → 9 → 1, with 4 nodes. The path 7 → 3 → 5 has only 3 nodes.
Example 2
Input: root = []
0Explanation: The tree has no nodes, so its depth is 0.
Example 3
Input: root = [-6, null, -6, -1]
3Explanation: Each node has one child, so the tree is a single path: −6, then −6 as its right child, then −1 as the left child of that node.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109- The tree has at most 1000 levels.
Clarifying questions
What you would ask an interviewer before writing any code.