The recursive method is trivial. Just record the root and go left and go right.
To do it iteratively, we need a stack to record the path. We go left until it's null. And pop the back out then go the back right. After doing this until stack is empty and root is null.
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL) return res;
vector<TreeNode*> stack;
while(root!=NULL||!stack.empty())
{
while(root!=NULL)
{
res.push_back(root->val);
stack.push_back(root);
root=root->left;
}
root=stack.back();
stack.pop_back();
root=root->right;
}
return res;
}