104.Maximum Depth of Binary Tree

Solution 1: accepted 1ms

DFS.

1
2
3
4
5
6
7
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
int leftDepth = maxDepth(root.left) + 1;
int rightDepth = maxDepth(root.right) + 1;
return Math.max(leftDepth, rightDepth);
}

Simplified 0ms

1
2
3
4
5
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}