-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patha_145.java
More file actions
32 lines (30 loc) · 848 Bytes
/
a_145.java
File metadata and controls
32 lines (30 loc) · 848 Bytes
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
package datastructure.tree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
/**
* 非递归实现二叉树的后序遍历
*/
public class a_145 {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<>();
if (root == null) return ret;
Stack<TreeNode> stack = new Stack<>();
stack.add(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
ret.add(node.val);
if (node.left != null) stack.add(node.left);
if (node.right != null) stack.add(node.right);
}
Collections.reverse(ret);
return ret;
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
}