Binary Tree Preorder Traversal (Java)
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public ArrayList preorderTraversal(TreeNode root) {
ArrayList returnList = new ArrayList();
if(root == null)
return returnList;
Stack stack = new Stack();
stack.push(root);
while(!stack.empty()){
TreeNode n = stack.pop();
returnList.add(n.val);
if(n.right != null){
stack.push(n.right);
}
if(n.left != null){
stack.push(n.left);
}
}
return returnList;
}
}