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