2014年1月14日星期二

Leetcoder - 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?

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> lst = new ArrayList<Integer>();
        Stack<TreeNode> fronties = new Stack<TreeNode>();
        if(root==null) {
            return lst;
        }
        fronties.push(root);
        Stack<TreeNode> output = new Stack<TreeNode>();
        while(!fronties.isEmpty()) {
            TreeNode top = fronties.pop();
            output.push(top);
            if(top.left!=null) {
                fronties.push(top.left);
            }
            if(top.right!=null) {
                fronties.push(top.right);
            }
        }
        while(!output.isEmpty()) {
            lst.add(output.pop().val);
        }
        return lst;
    }
}

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

没有评论:

发表评论