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].
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> list = new ArrayList<Integer>();
if(root == null)
return list;
Stack<TreeNode> stack1 = new Stack<TreeNode>();
stack1.push(root);
while(!stack1.isEmpty()) {
TreeNode current = stack1.pop();
list.add(current.val);
if(current.right != null)
stack1.add(current.right);
if(current.left != null)
stack1.add(current.left);
}
return list;
}
}