[LeetCode] #145 二叉树的后序遍历

给定一个二叉树,返回它的 后序 遍历。

输入: [1,null,2,3]

输出: [3,2,1]

参考[LeetCode] #144 二叉树的前序遍历[LeetCode] #94 二叉树的中序遍历

递归,使用辅助函数

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        preorder(root, res);
        return res;
    }

    public void preorder(TreeNode root, List<Integer> res) {
        if (root == null) return;
        preorder(root.left, res);
        preorder(root.right, res);
        res.add(root.val);
    }
}

递归,不使用辅助函数

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if (root == null) return res;
        res.addAll(postorderTraversal(root.left));
        res.addAll(postorderTraversal(root.right));
        res.add(root.val);
        return res;
    }
}

迭代1

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                res.add(root.val);
                stack.push(root);
                root = root.right;
            }
            root = stack.pop();
            root = root.left;
        }
        Collections.reverse(res);
        return res;
    }
}

迭代2

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        TreeNode pre = null;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.peek();
            if(root.right == null || root.right == pre){
                res.add(root.val);
                stack.pop();
                pre = root;
                root = null;
            }else root = root.right;
        }
        return res;
    }
}

知识点:

总结:

posted @ 2021-08-17 14:32  1243741754  阅读(30)  评论(0编辑  收藏  举报