-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjava_145.java
More file actions
63 lines (52 loc) · 1.18 KB
/
Copy pathjava_145.java
File metadata and controls
63 lines (52 loc) · 1.18 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
package leetcode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
* @author rwxn
*
*要求使用迭代,不能使用递归,改进后序遍历
*/
public class java_145 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<TreeNode>();
if (root == null) {
return null;
}
//先将根节点入栈,然后将右子树入栈,再将左子树入栈
stack.push(root);
while (stack.peek() != null) {
TreeNode node = stack.peek();
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
while (stack.peek() != null) {
list.add(stack.peek().val);//后序遍历第一个元素出栈并存入list中
stack.pop();
}
return null;
}
}