Skip to content

Commit 343c9f5

Browse files
Max depth of binary tree
1 parent 44ba403 commit 343c9f5

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package easy;
2+
3+
import classes.TreeNode;
4+
5+
/**104. Maximum Depth of Binary Tree QuestionEditorial Solution My Submissions
6+
Total Accepted: 163413
7+
Total Submissions: 333641
8+
Difficulty: Easy
9+
Given a binary tree, find its maximum depth.
10+
11+
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.*/
12+
public class MaximumDepthOfBinaryTree {
13+
/**Key to understand recursion, applies to generic recursion:
14+
* figure out all of the base cases/exit cases*/
15+
16+
//more verbose version
17+
public int maxDepth(TreeNode root) {
18+
if(root == null) return 0;
19+
int leftDepth = 0;
20+
if(root.left != null) leftDepth = maxDepth(root.left)+1;
21+
int rightDepth = 0;
22+
if(root.right != null) rightDepth = maxDepth(root.right)+1;
23+
return Math.max(1, Math.max(leftDepth, rightDepth));//the reason we need to max with 1 here is actually
24+
//for this case: if(root != null), it's implicit here, because we checked root.left != null and root.right != null
25+
//then it comes to root != null
26+
//example test case for the above scenario: nums = {1,1,1}
27+
}
28+
29+
//more concise version
30+
public int maxDepth_shorter_version(TreeNode root) {
31+
if(root == null) return 0;
32+
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
33+
}
34+
35+
}

0 commit comments

Comments
 (0)