1. preorder travel
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode *> myStack;
TreeNode * temp = root;
while(!myStack.empty() || temp != NULL){
if(temp != NULL){
myStack.push(temp);
result.push_back(temp->val);
temp = temp->left;
}
else{
TreeNode * node = myStack.top();
myStack.pop();
temp = node->right;
}
}
return result;
}
};
2. inorder travel
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode *> myStack;
TreeNode * temp = root;
while(!myStack.empty() || temp != NULL){
if(temp != NULL){
myStack.push(temp);
temp = temp->left;
}
else{
TreeNode * node = myStack.top();
myStack.pop();
result.push_back(temp->val);
temp = node->right;
}
}
return result;
}
};
3. postorder travel
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode *> myStack;
TreeNode * temp = root;
while(!myStack.empty() || temp != NULL){
if(temp != NULL){
myStack.push(temp);
result.insert(result.begin(),temp->val);
temp = temp->right;
}
else{
TreeNode * node = myStack.top();
myStack.pop();
temp = node->left;
}
}
return result;
}
};