2 / \ 1 3
5 / \ 3 10 / \ 1 4
Max depth in first is 1 and second is 2
This is one of the most common recursive question asked in interviews, with a simple implementation
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class MaxHeight {
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
return 1+ Math.max(maxDepth(root.left) , maxDepth(root.right));
}
}