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?
public ArrayList<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
ArrayList<Integer> arrayList = new ArrayList<>();
if(root!=null)
stack.push(root);
while(!stack.isEmpty())
{
TreeNode tmpNode = stack.pop();
arrayList.add(tmpNode.val);
if(tmpNode.right!=null) stack.push(tmpNode.right);
if(tmpNode.left!=null) stack.push(tmpNode.left);
}
return arrayList;
}