0%

structure-tree

树的操作

  • 树的构建
    • 广度优先遍历
      • 使用层次遍历构建(层次遍历结果中包含空的子节点)
    • 深度优先遍历
      • 使用先序遍历和中序遍历构建
      • 使用中序遍历和后序遍历构建
  • 树的遍历
    • 广度优先遍历
      • 层次遍历(层次遍历结果中不包含空的节点)
      • 层次遍历(层次遍历结果中包含空的子节点)
    • 深度优先遍历
      • 先序遍历
      • 中序遍历
      • 后序遍历

树的实现

Tree.javaview raw
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
package dsa.structure.ds701_tree;

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;

public class Tree {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode() {
}

TreeNode(int val) {
this.val = val;
}
}

public static TreeNode buildTreeByLevelOrder(Integer[] array) {
if (array.length == 0) {
return null;
}

java.util.Queue<TreeNode> queue = new java.util.LinkedList<>();
TreeNode root = new TreeNode(array[0]);
queue.offer(root);

Integer v = null;
int i = 1;
while (i < array.length) {
TreeNode node = queue.poll();

TreeNode left = i < array.length && (v = array[i++]) != null ? new TreeNode(v) : null;
TreeNode right = i < array.length && (v = array[i++]) != null ? new TreeNode(v) : null;

// 数组中不包含空节点的子节点的写法(不标准的完全二叉树含空节点的层次遍历)
node.left = left;
node.right = right;
if (left != null) {
queue.offer(left);
}
if (right != null) {
queue.offer(right);
}

// 数组中包含空节点的子节点的写法(标准的完全二叉树含空节点的层次遍历)
// if (node != null) {
// node.left = left;
// node.right = right;
// }
// queue.offer(left);
// queue.offer(right);
}

return root;
}

public static TreeNode buildTreeByPreOrderAndInOrder(Integer[] preorder, Integer[] inorder) {
// 前序遍历[根结点,左子树的前序遍历,右子树的前序遍历]
// 中序遍历[左子树的的中序遍历,根结点,右子树的的中序遍历]
// 先找到根结点(前序遍历的第一个)在中序遍历中的位置
// 然后利用根结点位置在中序遍历中进行分割求出左子树的中序遍历和右子树的中序遍历
// 然后利用左子树和右子树的长度在前序遍历求出左子树的前序遍历和右子树的前序遍历
// 然后再继续生成左子树和右子树

// 存储中序数组中结点到下标的映射,以便快速查找
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}

return buildTreeByPreOrderAndInOrder(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, map);
}

private static TreeNode buildTreeByPreOrderAndInOrder(Integer[] preorder, int preX, int preY,
Integer[] inorder, int inX, int inY, Map<Integer, Integer> map) {
if (preX > preY) {
return null;
}

int rootVal = preorder[preX];
TreeNode rootNode = new TreeNode(rootVal);

int rootIndex = map.get(rootVal);

int leftInX = inX;
int leftInY = rootIndex - 1;
int leftCount = leftInY - leftInX + 1;
int rightInX = rootIndex + 1;
int rightInY = inY;
int rightCount = rightInY - rightInX + 1;

if (leftCount > 0) {
int leftPreX = preX + 1;
int leftPreY = leftPreX + leftCount - 1;

rootNode.left = buildTreeByPreOrderAndInOrder(preorder, leftPreX, leftPreY, inorder, leftInX, leftInY, map);
}

if (rightCount > 0) {
int rightPreY = preY;
int rightPreX = rightPreY - rightCount + 1;

rootNode.right = buildTreeByPreOrderAndInOrder(preorder, rightPreX, rightPreY, inorder, rightInX, rightInY,
map);
}

return rootNode;
}

public static TreeNode buildTreeByInOrderAndPostOrder(Integer[] inorder, Integer[] postorder) {
// 后序遍历[左子树的前序遍历,右子树的前序遍历,根结点]
// 中序遍历[左子树的的中序遍历,根结点,右子树的的中序遍历]
// 先找到根结点(前序遍历的第一个)在中序遍历中的位置
// 然后利用根结点位置在中序遍历中进行分割求出左子树的中序遍历和右子树的中序遍历
// 然后利用左子树和右子树的长度在前序遍历求出左子树的前序遍历和右子树的前序遍历
// 然后再继续生成左子树和右子树

// 存储中序数组中结点到下标的映射,以便快速查找
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}

return buildTreeByInOrderAndPostOrder(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1, map);
}

private static TreeNode buildTreeByInOrderAndPostOrder(Integer[] inorder, int inX, int inY,
Integer[] postorder, int postX, int postY, Map<Integer, Integer> map) {
if (postX > postY) {
return null;
}

int rootVal = postorder[postY];
TreeNode rootNode = new TreeNode(rootVal);

int rootIndex = map.get(rootVal);

int leftInX = inX;
int leftInY = rootIndex - 1;
int leftCount = leftInY - leftInX + 1;
int rightInX = rootIndex + 1;
int rightInY = inY;
int rightCount = rightInY - rightInX + 1;

if (leftCount > 0) {
int leftPostX = postX;
int leftPostY = leftPostX + leftCount - 1;

rootNode.left = buildTreeByInOrderAndPostOrder(inorder, leftInX, leftInY, postorder, leftPostX, leftPostY,
map);
}

if (rightCount > 0) {
int rightPostY = postY - 1;
int rightPostX = rightPostY - rightCount + 1;

rootNode.right = buildTreeByInOrderAndPostOrder(inorder, rightInX, rightInY, postorder, rightPostX,
rightPostY, map);
}

return rootNode;
}

public static Integer[] visitTreeOfLevelOrderWithEmpty(TreeNode root) {
if (root == null) {
return new Integer[0];
}

java.util.LinkedList<Integer> list = new java.util.LinkedList<>();

java.util.Queue<TreeNode> queue = new java.util.LinkedList<>();
queue.offer(root);

while (!queue.isEmpty()) {
boolean hasValidNode = false;

int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();

if (node != null) {
list.add(node.val);

queue.offer(node.left);
queue.offer(node.right);

if (!hasValidNode) {
hasValidNode = node.left != null || node.right != null;
}
} else {
list.add(null);
}
}

if (!hasValidNode) {
// while (!queue.isEmpty()) {
// queue.poll();
// }

break;
}
}

while (!list.isEmpty() && list.get(list.size() - 1) == null) {
list.remove(list.size() - 1);
}

return list.toArray(new Integer[0]);
}

public static List<List<Integer>> visitTreeOfLevelOrderByLoop(TreeNode root) {
if (root == null) {
return new LinkedList<>();
}

List<List<Integer>> lists = new LinkedList<>();

List<TreeNode> nodes = new LinkedList<>();
nodes.add(root);

while (!nodes.isEmpty()) {
List<Integer> values = new LinkedList<>();
List<TreeNode> newNodes = new LinkedList<>();
for (TreeNode node : nodes) {
values.add(node.val);

if (node.left != null) {
newNodes.add(node.left);
}

if (node.right != null) {
newNodes.add(node.right);
}
}

lists.add(values);

nodes = newNodes;
}

return lists;
}

public static List<List<Integer>> visitTreeOfLevelOrderByRecursive(TreeNode root) {
if (root == null) {
return new LinkedList<>();
}

List<List<Integer>> lists = new LinkedList<>();

List<TreeNode> nodes = new LinkedList<>();
nodes.add(root);

visitTreeOfLevelOrderByRecursive(nodes, lists);

return lists;
}

private static void visitTreeOfLevelOrderByRecursive(List<TreeNode> nodes, List<List<Integer>> lists) {
if (nodes.isEmpty()) {
return;
}

List<Integer> values = new LinkedList<>();
List<TreeNode> newNodes = new LinkedList<>();
for (TreeNode node : nodes) {
values.add(node.val);

if (node.left != null) {
newNodes.add(node.left);
}

if (node.right != null) {
newNodes.add(node.right);
}
}

lists.add(values);

visitTreeOfLevelOrderByRecursive(newNodes, lists);
}

public static List<Integer> visitTreeOfPreOrderByRecursive(TreeNode root) {
if (root == null) {
return new LinkedList<>();
}

List<Integer> list = new LinkedList<>();

list.add(root.val);
list.addAll(visitTreeOfPreOrderByRecursive(root.left));
list.addAll(visitTreeOfPreOrderByRecursive(root.right));

return list;
}

public static List<Integer> visitTreeOfInOrderByRecursive(TreeNode root) {
if (root == null) {
return new LinkedList<>();
}

List<Integer> list = new LinkedList<>();

list.addAll(visitTreeOfInOrderByRecursive(root.left));
list.add(root.val);
list.addAll(visitTreeOfInOrderByRecursive(root.right));

return list;
}

public static List<Integer> visitTreeOfPostOrderByRecursive(TreeNode root) {
if (root == null) {
return new LinkedList<>();
}

List<Integer> list = new LinkedList<>();

list.addAll(visitTreeOfPostOrderByRecursive(root.left));
list.addAll(visitTreeOfPostOrderByRecursive(root.right));
list.add(root.val);

return list;
}

public static List<Integer> visitTreeOfLevelOrderByQueue1(TreeNode root) {
if (root == null) {
return new LinkedList<>();
}

List<Integer> list = new LinkedList<>();

Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);

while (!queue.isEmpty()) {
TreeNode node = queue.poll();

if (node.left != null) {
queue.offer(node.left);
}

if (node.right != null) {
queue.offer(node.right);
}

list.add(node.val);

}

return list;
}

public static List<List<Integer>> visitTreeOfLevelOrderByQueue2(TreeNode root) {
if (root == null) {
return new LinkedList<>();
}

List<List<Integer>> lists = new LinkedList<>();

Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);

while (!queue.isEmpty()) {
List<Integer> values = new LinkedList<>();

int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();

if (node.left != null) {
queue.offer(node.left);
}

if (node.right != null) {
queue.offer(node.right);
}

values.add(node.val);
}

lists.add(values);
}

return lists;
}

public static List<Integer> visitTreeOfPreOrderByStack(TreeNode root) {
if (root == null) {
return new LinkedList<>();
}

List<Integer> list = new LinkedList<>();

Deque<TreeNode> stack = new LinkedList<>();

TreeNode p = root;
while (p != null || !stack.isEmpty()) {
if (p != null) {
list.add(p.val);

stack.push(p);

p = p.left;
} else {
p = stack.pop();

p = p.right;
}
}

return list;
}

public static List<Integer> visitTreeOfInOrderByStack(TreeNode root) {
if (root == null) {
return new LinkedList<>();
}

List<Integer> list = new LinkedList<>();

Deque<TreeNode> stack = new LinkedList<>();

TreeNode p = root;
while (p != null || !stack.isEmpty()) {
if (p != null) {

stack.push(p);

p = p.left;
} else {
p = stack.pop();

list.add(p.val);

p = p.right;
}
}

return list;
}

public static List<Integer> visitTreeOfPostOrderByStack(TreeNode root) {
if (root == null) {
return new LinkedList<>();
}

List<Integer> list = new LinkedList<>();

Map<TreeNode, Integer> map = new HashMap<>();

Deque<TreeNode> stack = new LinkedList<>();

TreeNode p = root;
while (p != null || !stack.isEmpty()) {
if (p != null) {
Integer flag = map.getOrDefault(p, 0);

if (flag == 0) {
map.put(p, ++flag);

stack.push(p);

p = p.left;
} else if (flag == 1) {
map.put(p, ++flag);

stack.push(p);

p = p.right;
} else {
list.add(p.val);

// p = stack.isEmpty() ? null : stack.pop();
p = null;
}
} else {
p = stack.pop();
}
}

return list;
}

public static void main(String[] args) {
TreeTest.test();
}

public static class TreeTest {
private static Integer[] listToArray(List<Integer> list) {
return list.toArray(new Integer[0]);
}

private static Integer[] listsToArray(List<List<Integer>> lists) {
List<Integer> list = new LinkedList<>();
for (List<Integer> values : lists) {
list.addAll(values);
}

return list.toArray(new Integer[0]);
}

private static Integer[] levelarray = { 1, 3, 5, 7, null, 9, 11, 13, 15, null, null, null, 17 };
private static Integer[] levelorder = { 1, 3, 5, 7, 9, 11, 13, 15, 17 };
private static Integer[] preorder = { 1, 3, 7, 13, 15, 5, 9, 11, 17 };
private static Integer[] inorder = { 13, 7, 15, 3, 1, 9, 5, 11, 17 };
private static Integer[] postorder = { 13, 15, 7, 3, 9, 17, 11, 5, 1 };

private static void testTree(TreeNode tree) {
Integer[] result = null;
String tip = null;

result = Tree.visitTreeOfLevelOrderWithEmpty(tree);
tip = "树的层次遍历+空结点";
TestUtils.check(tip, result, levelarray);

result = listsToArray(Tree.visitTreeOfLevelOrderByLoop(tree));
tip = "树的层次遍历+循环版";
TestUtils.check(tip, result, levelorder);

result = listsToArray(Tree.visitTreeOfLevelOrderByRecursive(tree));
tip = "树的层次遍历+递归版";
TestUtils.check(tip, result, levelorder);

result = listToArray(Tree.visitTreeOfLevelOrderByQueue1(tree));
tip = "树的层次遍历+队列版1";
TestUtils.check(tip, result, levelorder);

result = listsToArray(Tree.visitTreeOfLevelOrderByQueue2(tree));
tip = "树的层次遍历+队列版2";
TestUtils.check(tip, result, levelorder);

result = listToArray(Tree.visitTreeOfPreOrderByRecursive(tree));
tip = "树的先序遍历+递归版";
TestUtils.check(tip, result, preorder);

result = listToArray(Tree.visitTreeOfPreOrderByStack(tree));
tip = "树的先序遍历+栈列版";
TestUtils.check(tip, result, preorder);

result = listToArray(Tree.visitTreeOfInOrderByRecursive(tree));
tip = "树的中序遍历+递归版";
TestUtils.check(tip, result, inorder);

result = listToArray(Tree.visitTreeOfInOrderByStack(tree));
tip = "树的中序遍历+栈列版";
TestUtils.check(tip, result, inorder);

result = listToArray(Tree.visitTreeOfPostOrderByRecursive(tree));
tip = "树的后序遍历+递归版";
TestUtils.check(tip, result, postorder);

result = listToArray(Tree.visitTreeOfPostOrderByStack(tree));
tip = "树的后序遍历+栈列版";
TestUtils.check(tip, result, postorder);
}

public static void test() {
test1();
test2();
test3();
}

public static void test1() {
TreeNode tree = Tree.buildTreeByLevelOrder(levelarray);
testTree(tree);
}

public static void test2() {
TreeNode tree = Tree.buildTreeByPreOrderAndInOrder(preorder, inorder);
testTree(tree);
}

public static void test3() {
TreeNode tree = Tree.buildTreeByInOrderAndPostOrder(inorder, postorder);
testTree(tree);
}
}

public static class TestUtils {

public static boolean check(String name, Object result, Object expect) {
boolean ok = java.util.Objects.deepEquals(result, expect);
printCheck(name, toString(result), toString(expect), ok);
return ok;
}

private static String toString(Object o) {
if (o instanceof Object[]) {
return java.util.Arrays.deepToString((Object[]) o);
} else if (o instanceof int[]) {
return java.util.Arrays.toString((int[]) o);
} else if (o instanceof double[]) {
return java.util.Arrays.toString((double[]) o);
} else if (o instanceof char[]) {
return java.util.Arrays.toString((char[]) o);
} else {
return java.util.Objects.toString(o);
}
}

public static void printCheck(String name, String result, String expect, boolean ok) {
System.out.println();
System.out.println("--->");

System.out.println("result: " + result);
System.out.println("expect: " + expect);

System.out.println();
if (ok) {
System.out.println("比较结果为: 正确(right)");
} else {
System.out.println("比较结果为: 错误(error)");
}

System.out.println("<---");
System.out.println();

if (!ok) {
throw new RuntimeException(String.format("ERROR: [%s]的测试失败", name));
}
}
}
}
只想买包辣条