-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution104.java
55 lines (46 loc) · 1.16 KB
/
Solution104.java
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
43
44
45
46
47
48
49
50
51
52
53
54
55
package algorithm.leetcode;
import java.util.LinkedList;
/**
* @author: mayuan
* @desc: 二叉树的深度
* @date: 2019/03/01
*/
public class Solution104 {
public int maxDepth(TreeNode root) {
if (null == root) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
public int maxDepth2(TreeNode root) {
if (null == root) {
return 0;
}
int depth = 0;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
// 记录当前层节点的数目
int size = queue.size();
while (size-- > 0) {
TreeNode cur = queue.pollFirst();
if (null != cur.left) {
queue.add(cur.left);
}
if (null != cur.right) {
queue.add(cur.right);
}
}
++depth;
}
return depth;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}