```
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
TreeNode *p = root, *tmp = nullptr;
while (p) {
res.push_back(p->val);
if (p->left) {
tmp = p->left;
while (tmp->right) tmp = tmp->right;
tmp->right = p->right;
p = p->left;
}
else {
p = p->right;
}
}
return res;
}
```