145. 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].

一刷
二刷
方法同144, 不过采用每次insert到数组头部,那么就变成了root, right, left的顺序

/**
 * 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 postorderTraversal(TreeNode root) {
        List res = new LinkedList<>();
        Stack stack = new Stack<>();
        while(root!=null || !stack.isEmpty()){
            if(root == null){
                root = stack.pop().left;
            }
            else{
                res.add(0, root.val);
                stack.push(root);
                root = root.right;
            }
        }
        return res;
    }
}

你可能感兴趣的:(145. Binary Tree Postorder Traversal)