Skip to content

Commit f73b757

Browse files
authored
Merge pull request gzc426#15 from V1ncentzzZ/V1ncentzzZ-patch-12
104. 二叉树的最大深度打卡
2 parents f674faa + c45d0bd commit f73b757

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
[104. 二叉树的最大深度][https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/]
2+
3+
给定一个二叉树,找出其最大深度。
4+
5+
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
6+
7+
说明: 叶子节点是指没有子节点的节点。
8+
9+
示例:
10+
给定二叉树 [3,9,20,null,null,15,7]
11+
```
12+
3
13+
/ \
14+
9 20
15+
/ \
16+
15 7
17+
```
18+
返回它的最大深度 3 。
19+
20+
```
21+
/**
22+
* Definition for a binary tree node.
23+
* public class TreeNode {
24+
* int val;
25+
* TreeNode left;
26+
* TreeNode right;
27+
* TreeNode(int x) { val = x; }
28+
* }
29+
*/
30+
class Solution {
31+
// public int maxDepth(TreeNode root) {
32+
// if(root == null) return 0;
33+
// return getDepth(root.left,root.right,1);
34+
// }
35+
36+
// public int getDepth(TreeNode node1,TreeNode node2,int high){
37+
// if(node1 == null && node2 == null) return high;
38+
// high++;
39+
// if(node1 == null) return getDepth(node2.left,node2.right,high);
40+
// if(node2 == null) return getDepth(node1.left,node1.right,high);
41+
// return Math.max(getDepth(node1.left,node1.right,high),getDepth(node2.left,node2.right,high));
42+
// }
43+
44+
public int maxDepth(TreeNode root) {
45+
if(root == null) return 0;
46+
int left = maxDepth(root.left);
47+
int right = maxDepth(root.right);
48+
return 1 + (left > right ? left : right);
49+
}
50+
}
51+
```

0 commit comments

Comments
 (0)