利用递归简单的实现:

class Solution {
public:
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> res;
        helper(root, res);
        return res;
    }
private:    
    void helper(TreeNode * root ,vector<int>& res) {
        if(root == NULL)return ;
        res.push_back(root->val);
        helper(root->left , res);
        helper(root->right,  res);

    }
};