leetcode 145. Binary Tree Postorder Traversal

Posted exhausttolive

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 ]

以上是关于leetcode 145. Binary Tree Postorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 145. Binary Tree Postorder Traversal

LeetCode 145:Binary Tree Postorder Traversal

leetcode145. Binary Tree Postorder Traversal

LeetCode 145: Binary Tree Postorder Traversal

leetcode No145. Binary Tree Postorder Traversal

LeetCode OJ 145. Binary Tree Postorder Traversal