05 August 2008
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree
,1
[3,9,20,null,null,15,7]
1
2
3
4
5
3
/ \
9 20
/ \
15 7
return its depth = 3.
给一颗二叉树,找到其最大的深度并返回。可以用递归,DFS和BFS来做。
递归做法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));//只要root不为null,深度至少为1
}
}
DFS,用两个stack,一个用来记录Tree的结点,另一个用来记录最大深度,不推荐,了解下即可。
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
Stack<TreeNode> stack = new Stack<>();//存储树节点
Stack<Integer> depth = new Stack<>();//存储树的深度
stack.push(root);//初始化
depth.push(1);//root不为null,则深度至少为1
int maxDepth = 0;
while (!stack.isEmpty()) {//只要stack中的元素还没有弹完
int temp = depth.pop();//每轮先弹出上一轮的“最大深度“进行比较
maxDepth = Math.max(temp, maxDepth);
TreeNode node = stack.pop();
if (node.left != null) {
stack.push(node.left);
depth.push(temp + 1);//在上一轮最大值的基础上,DFS多了一层
}
if (node.right != null) {
stack.push(node.right);
depth.push(temp + 1);
}
}
return maxDepth;
}
}
BFS,用Queue来实现,推荐的BFS方式
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
/**
* Definition for a binary tree node.
* public 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;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int depth = 0;
while (!queue.isEmpty()) {
int currentSize = queue.size();
for (int i = 0; i < currentSize; i++) {
TreeNode node = queue.poll();//node本身不用做任何检查
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
depth++;
}
return depth;
}
}