[leetcode] 145. 二叉树的后序遍历

145. 二叉树的后序遍历

递归写法

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        dfs(root, list);
        return list;
    }

    public void dfs(TreeNode node, List<Integer> ans) {
        if (node.left != null) dfs(node.left, ans);
        if (node.right != null) dfs(node.right, ans);
        ans.add(node.val);
    }
}

非递归写法
还是比较难的,要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。如果P不存在左孩子和右孩子,则可以直接访问它;或者P存在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了,则同样可以直接访问该结点。若非上述两种情况,则将P的右孩子和左孩子依次入栈,这样就保证了每次取栈顶元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子都在根结点前面被访问。

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();

        TreeNode pre = null;
        stack.push(root);
        while (!stack.isEmpty()) {
            root = stack.peek();
            if ((root.left == null && root.right == null) || (pre != null && (pre == root.left || pre == root.right))) {//如果当前结点没有孩子结点或者孩子节点都已被访问过 
                list.add(root.val);
                stack.pop();
                pre = root;
            } else {
                if (root.right != null) stack.push(root.right);
                if (root.left != null) stack.push(root.left);
            }
        }

        return list;
    }
}
posted @ 2018-08-07 23:29  ACBingo  阅读(141)  评论(0编辑  收藏  举报