leetcode 145. Binary Tree Postorder Traversal
I never tried before to implement postorder traversal of binary tree with non-recursive method.
So the ugly handwork is attached below.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<>();
Stack<TreeNode> s = new Stack<>();
Set<TreeNode> poped = new HashSet<>();
TreeNode node = root;
while (node != null || !s.isEmpty()) {
while (node != null) {
s.add(node);
node = node.left;
}
node = s.pop();
if (poped.contains(node)) {
ret.add(node.val);
node = null;
}
else {
poped.add(node);
s.add(node);
node = node.right;
}
}
return ret;
}
}
But In the discuss area, I saw a much better version for pre-order, in-order and post-order non-recursive implementation.
I'll write an article, the link is.... [TO DO ]