Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Source
public int maxDepth(TreeNode root) {
int left, right;
if(root == null) return 0;
if(root.left == null && root.right == null){
return 1;
}
if(root.left == null){
left = Integer.MIN_VALUE;
}
else left = maxDepth(root.left);
if(root.right == null){
right = Integer.MIN_VALUE;
}
else right = maxDepth(root.right);
return Math.max(left, right)+1;
}
Test
public static void main(String[] args){
TreeNode a = new TreeNode(5);
a.left = new TreeNode(4);
a.right = new TreeNode(8);
a.left.left = new TreeNode(11);
a.left.left.left = new TreeNode(7);
a.left.left.right = new TreeNode(2);
a.right.left = new TreeNode(13);
a.right.right = new TreeNode(4);
a.right.right.right = new TreeNode(1);
System.out.println(new Solution().maxDepth(a));
}