二叉树的遍历
- 非递归 颜色判定法 中序遍历 迭代法,统一写法
/**
* 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 {
class ColorNode {
TreeNode node;
boolean flag; // true 为访问过; false 为未访问.
ColorNode (TreeNode node, boolean flag) {
this.node = node;
this.flag = flag;
}
}
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) return new ArrayList<Integer>();
List<Integer> res = new ArrayList<>();
ArrayDeque<ColorNode> stack = new ArrayDeque<>();
stack.offerFirst(new ColorNode(root, false));
while (stack.size() != 0) {
ColorNode cn = stack.pollFirst();
if (cn.flag == false) {
//以下可以更改顺序
if (cn.node.right != null) stack.offerFirst(new ColorNode(cn.node.right, false));
stack.offerFirst(new ColorNode(cn.node, true));
if (cn.node.left != null) stack.offerFirst(new ColorNode(cn.node.left, false));
} else {
res.add(cn.node.val);
}
}
return res;
}
}
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
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
递归法 统一写法
/**
* 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 {
List<Integer> res=new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if(root==null) return res;
//以下可以更改顺序
if(root.left!=null) postorderTraversal(root.left);
if(root.right!=null) postorderTraversal(root.right);
res.add(root.val);
return res;
}
}
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
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
编辑 (opens new window)
上次更新: 2024/02/22, 14:03:19