Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit343c9f5

Browse files
Max depth of binary tree
1 parent44ba403 commit343c9f5

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
packageeasy;
2+
3+
importclasses.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+
publicclassMaximumDepthOfBinaryTree {
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+
publicintmaxDepth(TreeNoderoot) {
18+
if(root ==null)return0;
19+
intleftDepth =0;
20+
if(root.left !=null)leftDepth =maxDepth(root.left)+1;
21+
intrightDepth =0;
22+
if(root.right !=null)rightDepth =maxDepth(root.right)+1;
23+
returnMath.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+
publicintmaxDepth_shorter_version(TreeNoderoot) {
31+
if(root ==null)return0;
32+
returnMath.max(maxDepth(root.left),maxDepth(root.right)) +1;
33+
}
34+
35+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp