Maximum Depth of Binary Tree:
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.
Input: root = [3,9,20,null,null,15,7]
Output: 3
Input: root = [1,null,2]
Output: 2
[0, 10^4]
.-100 <= Node.val <= 100
Try this Problem on your own or check similar problems:
public int maxDepth(TreeNode root) {
if(root == null) return 0;
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
Remember how we used BFS for the shortest path to leaf node (min depth) in
Minimum Depth of Binary Tree
, well in this case the we can use DFS since by the problem statement we have to find the longest root-to-leaf path so the optimization we did with BFS is not useful for this problem. The problem is trivial we check left and right subtree depth and have a base case for root == null
to start iterating back from the recursion stack, we just return the deeper subtree.
Don’t settle for anything less than the crown. Join our newsletter and become the King of Interviews! Click here to join now and get the latest updates.