Leecode 145. 二叉树的后序遍历

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

示例:

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

输出: [3,2,1]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

import java.util.Stack;
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> res = new ArrayList();
        if(root==null) return res;
        Stack<TreeNode> st = new Stack();
        while(!st.isEmpty()||root!=null){
            while(root!=null) {
                st.add(root);
                res.add(root.val);
                root = root.right;  //先遍历右节点
            }
            root = st.pop();
            root =root.left;        //再左节点
        }
        Collections.reverse(res);   //反转链表
        return res;

    }
}

递归:

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

    public void deal(TreeNode root){
        if(root==null) return;
        deal(root.left);
        deal(root.right);
        res.add(root.val);
    }
}
原文地址:https://www.cnblogs.com/kpwong/p/14651195.html