-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinaryTreePostorderTraversal.java
More file actions
66 lines (52 loc) · 2.03 KB
/
Copy pathBinaryTreePostorderTraversal.java
File metadata and controls
66 lines (52 loc) · 2.03 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
// Given a binary tree, return the postorder traversal of its nodes' values.
// Recursive solution is trivial, could you do it iteratively?
// See: https://leetcode.com/problems/binary-tree-postorder-traversal/
package leetcode.tree;
import static leetcode.util.tree.BinTreeUtil.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import leetcode.util.tree.TreeNode;
public class BinaryTreePostorderTraversal {
// TODO: Add more effective stack based solution
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null) return res;
Map<TreeNode, Boolean> hasChilren = new HashMap<>();
Stack<TreeNode> s = new Stack<>();
s.add(root);
while (!s.isEmpty()) {
TreeNode curr = s.peek();
if ((curr.left == null && curr.right == null) ^ !hasChilren.getOrDefault(curr, true)) {
res.add(s.pop().val);
continue;
}
if (curr.right != null)
s.add(curr.right);
if(curr.left != null)
s.add(curr.left);
hasChilren.put(curr, false);
}
return res;
}
@SuppressWarnings("unused")
private void postOrd(TreeNode root) {
if (root == null) return;
postOrd(root.left);
postOrd(root.right);
System.out.println(root.val);
}
public static void main(String[] args) {
BinaryTreePostorderTraversal sln = new BinaryTreePostorderTraversal();
TreeNode t1 = initTree(1, 0, 4, 2, 3, 5, null);
TreeNode t2 = initTree(5, 3, 7, 1, 4, 6, 8);
// printInorder(t2);
// sln.postOrd(t2);
System.out.println(sln.postorderTraversal(t1));
System.out.println(sln.postorderTraversal(t2));
System.out.println(sln.postorderTraversal(null));
System.out.println(sln.postorderTraversal(initTree(1)));
}
}