-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathT6.java
More file actions
81 lines (74 loc) · 2.46 KB
/
T6.java
File metadata and controls
81 lines (74 loc) · 2.46 KB
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
package testCode;
import java.util.ArrayList;
import java.util.Stack;
public class T6 {
public static final void main(String args[]) {
ArrayList<Integer> result = new ArrayList<>();
result.add(null);
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
System.out.print(postorderTraversal(root).size());
}
public static ArrayList<Integer> postorderTraversal(TreeNode root) {
if (null == root) {
return new ArrayList<Integer>();
}
Stack<TreeNode> stack = new Stack<>();
ArrayList<Integer> result = new ArrayList<>();
TreeNode currentNode = root;
boolean hasChildNode = false;
while (true) {
if (null != currentNode && Integer.MAX_VALUE != currentNode.val) {
stack.push(currentNode);
}
if (null != currentNode.right && Integer.MAX_VALUE != currentNode.right.val) {
stack.push(currentNode.right);
hasChildNode = true;
}
if (null != currentNode.left && Integer.MAX_VALUE != currentNode.left.val) {
stack.push(currentNode.left);
hasChildNode = true;
}
if (hasChildNode) {
currentNode = stack.pop();
if (0 == stack.size()) {
result.add(currentNode.val);
return result;
}
hasChildNode = false;
} else {
result.add(currentNode.val);
stack.pop();
currentNode.val = Integer.MAX_VALUE;
if (0 == stack.size()) {
return result;
}
currentNode = stack.pop();
}
}
}
public ArrayList<Integer> postorderTraversal1(TreeNode root) {
if (null == root) {
return new ArrayList<Integer>();
}
ArrayList<Integer> left = postorderTraversal(root.left);
ArrayList<Integer> right = postorderTraversal(root.right);
ArrayList<Integer> result = new ArrayList<>();
if (0 < left.size()) {
result.addAll(left);
}
if (0 < right.size()) {
result.addAll(right);
}
result.add(root.val);
return result;
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}