Simplest Solution using one stack (just change order for other traversals


#1

vector Solution::preorderTraversal(TreeNode* root) {
vector ans;
stack<pair<TreeNode*, int>> s;
s.push({root, 0});
while (s.empty() == false) {
pair<TreeNode*, int> temp = s.top();
TreeNode* curr = temp.first;
int state = temp.second;
s.pop();
if (curr == NULL || state == 3) continue;
s.push({curr, state + 1});
// change order of these lines according to different traversals
if (state == 0) ans.push_back(curr->val);
else if (state == 1) s.push({curr->left, 0});
else if (state == 2) s.push({curr->right ,0});
}
return ans;
}