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?
Subscribe to see which companies asked this question
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if(root != null){
preorder(root,list);
}
return list;
}
private void preorder(TreeNode root,List<Integer> list){
list.add(root.val);
if(root.left!=null){
preorder(root.left,list);
}
if(root.right!=null){
preorder(root.right,list);
}
}
}