1. 程式人生 > >[Leetcode] 145. 二叉樹的後序遍歷 java

[Leetcode] 145. 二叉樹的後序遍歷 java

 給定一個二叉樹,返回它的 後序 遍歷。

示例:

輸入: [1,null,2,3]  
   1
    \
     2
    /
   3 

輸出: [3,2,1]

進階: 遞迴演算法很簡單,你可以通過迭代演算法完成嗎?

一、遞迴

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list=new ArrayList<>();
        if(root==null) return list;
        postorderTree(root,list);
        return list;
    }
    public void postorderTree(TreeNode root,List<Integer> list){
        if(root==null) return ;
        postorderTree(root.left,list);
        postorderTree(root.right,list);
        list.add(root.val);
    }
}

二、迭代

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list=new ArrayList<>();
        Stack<TreeNode> stack=new Stack<>();
        if(root==null) return list;
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode curr=stack.pop();
            if(curr.left==null&&curr.right==null){
                list.add(curr.val);
                continue;
            }
            stack.push(new TreeNode(curr.val));
            if(curr.right!=null) stack.push(curr.right);
            if(curr.left!=null) stack.push(curr.left);
        }
        return list;
    }
}