随意随想

知其然,知其所以然

0%

树的迭代遍历统一写法

刚学完树的迭代遍历,但是不一样的写法,会导致人大佬迷糊记不清,所以在此纪录一下统一的写法

里面的方法使用到的是空标记法,单判断到空字节,则证明需要处理空节点了

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
 /**
* 前序遍历
* 中、左、右
*/
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
//栈不为空
while (!stack.isEmpty()) {
TreeNode node = stack.peek();
if (node != null) {
stack.pop();
stack.push(node.rigth);//右
stack.push(node.left);//左
stack.push(node); //中
stack.push(null);
} else {
stack.pop();//弹出空元素
node = stack.peek();
if (node != null) {
result.add(node.val);
stack.pop();
}
}
}
return result;
}

/**
* 后续遍历
* 左、右、中
*/
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
//栈不为空
while (!stack.isEmpty()) {
TreeNode node = stack.peek();
if (node != null) {
stack.pop();
stack.push(node); //中
stack.push(null);
stack.push(node.rigth);//右
stack.push(node.left);//左
} else {
stack.pop();//弹出空元素
node = stack.peek();
if (node != null) {
result.add(node.val);
stack.pop();
}
}
}
return result;
}



/**
* 中序遍历
* 左、中、右
*/
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
//栈不为空
while (!stack.isEmpty()) {
TreeNode node = stack.peek();
if (node != null) {
stack.pop();
stack.push(node.rigth);//右
stack.push(node); //中
stack.push(null);
stack.push(node.left);//左
} else {
stack.pop();//弹出空元素
node = stack.peek();
if (node != null) {
result.add(node.val);
stack.pop();
}
}
}
return result;
}