Given the root
of a binary tree, return its maximum depth.
A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: 3
Example 2:
Input: root = [1,null,2] Output: 2
Constraints:
- The number of nodes in the tree is in the range
[0, 104]
. -100 <= Node.val <= 100
Solution
Maximum Depth of binary tree can be thought as same as height of binary tree. You can think of height as number of nodes from root to farthest leaf (with both root and leaf included).
Once you understand the problem, as I have done with other binary tree problems, I’ll give recursion a try. So height of a binary tree can be maximum of height of left sub tree and right sub tree and we need to add one to it to account for parent/root node.
Below is the Java code for this.
public int maxDepth(TreeNode root) {
if (root == null) return 0;
else return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
Pretty sleek right. 🙂
Let’s check time and space complexity of it.
