-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTreePostorderTraversal.java
50 lines (43 loc) · 1.38 KB
/
BinaryTreePostorderTraversal.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
package leetcode;
import utils.TreeNode;
import utils.Trees;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
/**
* BinaryTreePostorderTraversal
* https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
*
* @since 2020-09-29
*/
public class BinaryTreePostorderTraversal {
public static void main(String[] args) {
Integer[] values = {1, null, 2, 3};
TreeNode head = Trees.fromIntegers(values);
BinaryTreePostorderTraversal sol = new BinaryTreePostorderTraversal();
System.out.println(sol.postorderTraversal(head));
}
public List<Integer> postorderTraversal(TreeNode root) {
Stack<Object> stack = new Stack<>();
stack.push(root);
List<Integer> result = new LinkedList<>();
while (!stack.isEmpty()) {
Object curr = stack.pop();
if (curr == null) {
// skip
} else if (curr instanceof TreeNode) {
TreeNode node = (TreeNode) curr;
if (node.left == null && node.right == null) {
result.add(node.val);
} else {
stack.add(node.val);
stack.add(node.right);
stack.add(node.left);
}
} else {
result.add((int) curr);
}
}
return result;
}
}