public List<Integer> preorderTraversal(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        if (root == null) return res;
        Stack<TreeNode> s = new Stack<TreeNode>();
        s.add(root);
        while (!s.isEmpty()) {
            TreeNode p = s.pop();
            res.add(p.val);
            if (p.right != null) s.push(p.right);
            if (p.left != null) s.push(p.left);
        }
        return res;
    }