145. 二叉树的后序遍历

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

示例:
输入: [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 postorderTraversal(TreeNode root) {
        Listans = new LinkedList<>();
        post(root,ans);
        return ans;
    }
    public void post(TreeNode root, Listans){
        if(root == null)
            return;
        if(root.left != null){
            post(root.left,ans);
        }
        if(root.right != null){
            post(root.right,ans);
        }
        ans.add(root.val);
    }
}

迭代:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
     public List postorderTraversal(TreeNode root) {
        LinkedList ans = new LinkedList<>();
        LinkedList stack = new LinkedList<>();
        if(root == null)
            return ans;
        stack.add(root);
        while (!stack.isEmpty()){
            TreeNode node = stack.pollLast();
            ans.addFirst(node.val);
            if(node.left != null){
                stack.add(node.left);
            }
            if(node.right != null){
                stack.add(node.right);
            }
        }
        return ans;
    }
}

你可能感兴趣的:(145. 二叉树的后序遍历)