2014年2月9日星期日

LeetCoder - Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
   1
    \
     2
    /
   3
return [1,2,3].
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> preorderTraversal(TreeNode root) {
        ArrayList<Integer> ret = new ArrayList<Integer>();
        if(root==null) {
            return ret;
        }
        Stack<TreeNode> lst = new Stack<TreeNode>();
        lst.push(root);
        while(!lst.isEmpty()) {
            TreeNode node = lst.pop();
            ret.add(node.val);
            if(node.right!=null) lst.push(node.right);
            if(node.left!=null) lst.push(node.left);
        }
        return ret;
    }
}

没有评论:

发表评论