1. 程式人生 > 其它 >[LeetCode] #145 二叉樹的後序遍歷

[LeetCode] #145 二叉樹的後序遍歷

[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;
    }
}

知識點:

總結: