import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    public int[] preorderTraversal (TreeNode root) {
        ArrayList<Integer> arr=new ArrayList<>();
        preorder(root,arr);
        int[] num=new int[arr.size()];
        for(int i=0;i<arr.size();i++){
            num[i]=arr.get(i);
        }
        return num;
    }
    private void preorder(TreeNode root,ArrayList<Integer> arr){
        if(root==null){
            return;
        }
        arr.add(root.val);
        preorder(root.left,arr);
        preorder(root.right,arr);
    }
}