forked from Gerkins/arithmeticSum
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathBinaryTreeMaxDepthWidth.java
125 lines (105 loc) · 3.19 KB
/
BinaryTreeMaxDepthWidth.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import java.util.ArrayDeque;
import java.util.Queue;
/**
* Created by lrkin on 2016/10/26.
* 求二叉树的深度和广度
*/
public class BinaryTreeMaxDepthWidth {
static class TreeNode {
char val;
TreeNode left = null;
TreeNode right = null;
public TreeNode(char val) {
this.val = val;
}
public TreeNode(char val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
/**
* 获取最大深度
* <p>
* 记忆点:递归
*
* @param root
* @return
*/
public static int getMaxDepth(TreeNode root) {
if (root == null) {
return 0;
} else {
int left = getMaxDepth(root.left);
int right = getMaxDepth(root.right);
return 1 + Math.max(left, right);
}
}
/**
* 获取最大宽度
* <p>
* <p>
* 记忆点:采用队列这种数据结构,来记录每一层的宽度,遍历即可
*
* @param root
* @return
*/
public static int getMaxWidth(TreeNode root) {
if (root == null)
return 0;
//获取队列
Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
int maxWidth = 1;
queue.add(root);
//循环
while (true) {
int size = queue.size();
if (size == 0) {
break;
}
while (size > 0) {
//不为零,那么一直poll完这一层的所有节点为止
TreeNode node = queue.poll();
size--;
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
//每一层,都更新maxWidth;
// maxWidth = Math.max(maxWidth, size);这样写错误,因为size递减
maxWidth = Math.max(maxWidth, queue.size());
}
return maxWidth;
}
public static TreeNode initBinaryTree() {
TreeNode J = new TreeNode('a', null, null);
TreeNode H = new TreeNode('b', null, null);
TreeNode G = new TreeNode('c', null, null);
TreeNode F = new TreeNode('d', null, J);
TreeNode E = new TreeNode('e', H, null);
TreeNode D = new TreeNode('g', null, G);
TreeNode C = new TreeNode('w', F, null);
TreeNode B = new TreeNode('h', D, E);
TreeNode A = new TreeNode('z', B, C);
return A; //返回根节点
//
// Node J = new Node(8, null, null);
// Node H = new Node(4, null, null);
// Node G = new Node(2, null, null);
// Node F = new Node(7, null, J);
// Node E = new Node(5, H, null);
// Node D = new Node(1, null, G);
// Node C = new Node(9, F, null);
// Node B = new Node(3, D, E);
// Node A = new Node(6, B, C);
// return A; //返回根节点
}
public static void main(String[] args) {
TreeNode root = initBinaryTree();
System.out.println(getMaxDepth(root));
System.out.println(getMaxWidth(root));
}
}