LC145. Binary Tree Postorder Traversal

Posted by freeCookie🍪 on January 18, 2017

LC145. Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes’ values.

For example: Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

啊这题这不是Morries Traversal 么… 见LC 99

Stack solution:

Pre/In/Post order

利用postorder是preorder的倒序。先将pre改成中右左,再reverse.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 
public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<Integer> res = new LinkedList<>();
        Deque<TreeNode> stack = new ArrayDeque<>();
        if(root == null)    return res;
        TreeNode p = root;
        while(!stack.isEmpty() || p != null){
            if(p != null){
                stack.push(p);
                res.addFirst(p.val);
                p = p.right;
            }else{
                TreeNode n = stack.pop();
                p = n.left;
            }
        } // while
        return res;
    }
}