2014年4月28日 星期一

[LeetCode] Binary Tree Preorder Traversal

Problem:
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?
Solution:O(n)
public class Solution {
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        if(root == null)
     return new ArrayList<Integer>();
 ArrayList<Integer> list = new ArrayList<>();
 Stack<TreeNode> stack = new Stack<>();
 stack.push(root);
         
        while(!stack.isEmpty()){
     TreeNode node = stack.pop();
     list.add(node.val);
     if(node.right!=null)
         stack.push(node.right);
          
     if(node.left!=null)
         stack.push(node.left);
 }
         
 return list;
    }
}

沒有留言:

張貼留言