美文网首页
145. Binary Tree Postorder Trave

145. Binary Tree Postorder Trave

作者: DrunkPian0 | 来源:发表于2017-07-29 23:52 被阅读19次

这题跟144和94一样了,但这题是hard。递归写法都是一致的,这里贴一下迭代写法,摘自https://discuss.leetcode.com/topic/30632/preorder-inorder-and-postorder-iteratively-summarization/2
很多人说他在cheating,我模拟了一下,好像没什么问题,不深究了。

//Post Order Traverse
public List<Integer> postorderTraversal(TreeNode root) {
    LinkedList<Integer> result = new LinkedList<>();
    Deque<TreeNode> stack = new ArrayDeque<>();
    TreeNode p = root;
    while(!stack.isEmpty() || p != null) {
        if(p != null) {
            stack.push(p);
            result.addFirst(p.val);  // Reverse the process of preorder
            p = p.right;             // Reverse the process of preorder
        } else {
            TreeNode node = stack.pop();
            p = node.left;           // Reverse the process of preorder
        }
    }
    return result;
}

跟preorder对比:

    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Deque<TreeNode> stack = new ArrayDeque<>();
        TreeNode p = root;
        while(!stack.isEmpty() || p != null) {
            if(p != null) {
                stack.push(p);
                result.add(p.val);  // Add before going to children
                p = p.left;
            } else {
                TreeNode node = stack.pop();
                p = node.right;
            }
        }
        return result;
    }

相关文章

网友评论

      本文标题:145. Binary Tree Postorder Trave

      本文链接:https://www.haomeiwen.com/subject/qathlxtx.html