Given a binary tree, return the preorder traversal of its nodes' values.
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<Integer>();
if(root==null){
return result;
}
List<Integer> left=preorderTraversal(root.left);
List<Integer> right=preorderTraversal(root.right);
result.add(root.val);
result.addAll(left);
result.addAll(right);
return result;
}
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<Integer>();
Helper(result,root);
return result;
}
public void Helper(List<Integer> result,TreeNode root){
if(root==null){
return;
}
result.add(root.val);
Helper(result,root.left);
Helper(result,root.right);
}
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 current=stack.pop();
result.add(current.val);
if(current.right!=null){
stack.push(current.right);
}
if(current.left!=null){
stack.push(current.left);
}
}
return result;
}