import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型ArrayList
     */
public ArrayList<Integer> preorderTraversal (TreeNode root) {
        // write code here
        ArrayList<Integer> res = new ArrayList<>();
 
        if (root == null) {
            return res;
        }
 
        Stack<TreeNode> stk = new Stack<>();
        stk.push(root);
        while (!stk.empty()) {
            TreeNode node = stk.pop();
            res.add(node.val);
 
            if (node.right != null) {
                stk.push(node.right);
            }
            if (node.left != null) {
                stk.push(node.left);
            }
        }
 
        return res;
    }
}