Binary Tree Postorder Traversal

2016-11-26  本文已影响0人  无为无悔

Note: Recursive solution is trivial, could you do it iteratively?


import java.util.*;

public class Solution {
    public List<Integer> postorderTraverse(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null)
            return result;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode p = root;
        Map<TreeNode, Boolean> map = new HashMap<>();
        while (!stack.isEmpty() || p != null) {
            if (p != null) {
                // 右子树已被压栈一次
                if (map.containsKey(p)) {
                    p = null;
                    continue;
                }
                stack.push(p);
                if (!map.containsKey(p))
                    map.put(p, false);
                p = p.left;
            } else {
                p = stack.pop();
                // 有右子树的节点弹出且已被访问一次,直接输出
                if ((map.get(p) == true && p.right != null) || p.right == null) {
                    result.add(p.val);
                }
                // 包含右子树的节点,第一次弹栈后,不输出,而再次入栈,确保右子树访问完,能第二次访问该节点
                if (p.right != null && map.containsKey(p) && map.get(p) == false) {
                    stack.push(p);
                    map.put(p, true);
                }
                p = p.right;
            }
        }
        return result;
    }
}

上一篇 下一篇

猜你喜欢

热点阅读