forked from algorithm024/algorithm024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxDepth_104.java
More file actions
42 lines (37 loc) · 969 Bytes
/
Copy pathMaxDepth_104.java
File metadata and controls
42 lines (37 loc) · 969 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class MaxDepth_104 {
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
/**
* 使用递归方式求解
* @param root
* @return
*/
public int maxDepth1(TreeNode root) {
// 递归终止条件
if (root == null) {
return 0;
}
// 执行当前层的逻辑,并下探到下一层
return Math.max(maxDepth1(root.left), maxDepth1(root.right)) + 1;
}
/**
* maxDepth1的精简写法
* @param root
* @return
*/
public int maxDepth2(TreeNode root) {
return (root != null) ? Math.max(maxDepth2(root.left), maxDepth2(root.right)) + 1 : 0;
}
}