forked from kexun/sort
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PostorderTree.java
96 lines (77 loc) · 1.8 KB
/
PostorderTree.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
package com.demo;
import java.util.ArrayList;
import java.util.Stack;
public class PostorderTree {
public static void main(String[] args) {
TreeNode root = new PostorderTree().new TreeNode(3);
TreeNode root1 = new PostorderTree().new TreeNode(1);
TreeNode root2 = new PostorderTree().new TreeNode(2);
root.left = root1;
root.right = root2;
PostorderTree p = new PostorderTree();
ArrayList<Integer> list = p.postorderTraversal2(root);
for (Integer i : list) {
System.out.println(i);
}
}
/**
* 最常用的递归方式
* @param root
* @return
*/
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (root != null) {
traversal(root, list);
}
return list;
}
public void traversal(TreeNode root, ArrayList<Integer> list) {
if (root == null) {
return;
}
traversal(root.left, list);
traversal(root.right, list);
list.add(root.val);
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
/**
* 非递归,迭代的方式
* @param root
* @return
*/
public ArrayList<Integer> postorderTraversal2(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (root != null) {
traversal2(root, list);
}
return list;
}
public void traversal2(TreeNode root, ArrayList<Integer> list) {
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode top = stack.peek();
if (top.left == null && top.right == null) {
list.add(top.val);
stack.pop();
} else {
if (top.right != null) {
stack.push(top.right);
top.right = null;
}
if (top.left != null) {
stack.push(top.left);
top.left = null;
}
}
}
}
}