Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
if(root == NULL)
return res;
st.push(root);
while(!st.empty()){
TreeNode* temp = st.top();
st.pop();
res.push_back(temp->val);
if(temp->right != NULL)
st.push(temp->right);
if(temp->left != NULL)
st.push(temp->left);
}
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment