Last active
September 12, 2018 10:02
-
-
Save pwxcoo/7cff67a84601ea7c79dfe49717c3fc85 to your computer and use it in GitHub Desktop.
Binary Tree Traversal of Iteration (non-recursion)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
vector<int> inorderTraversal(TreeNode* root) { | |
stack<TreeNode*> st; | |
vector<int> res; | |
auto now = root; | |
while(!st.empty() || now) | |
{ | |
while(now) | |
{ | |
st.push(now); | |
now = now->left; | |
} | |
if(!st.empty()) | |
{ | |
now = st.top(); st.pop(); | |
res.push_back(now->val); | |
now = now->right; | |
} | |
} | |
return res; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
vector<int> postorderTraversal(TreeNode* root) { | |
stack<TreeNode*> st; | |
vector<int> res; | |
TreeNode* now = root; | |
TreeNode* last = NULL; | |
while(!st.empty() || now) | |
{ | |
while(now) | |
{ | |
st.push(now); | |
now = now->left; | |
} | |
if (!st.empty()) | |
{ | |
now = st.top(); | |
if (!now->right || now->right == last) | |
{ | |
res.push_back(now->val); | |
st.pop(); | |
last = now; | |
now = NULL; | |
} | |
else | |
{ | |
now = now->right; | |
} | |
} | |
} | |
return res; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
vector<int> preorderTraversal(TreeNode* root) { | |
vector<int> res; | |
stack<TreeNode*> st; | |
TreeNode* now = root; | |
while(!st.empty() || now != NULL) | |
{ | |
while(now) | |
{ | |
st.push(now); | |
res.push_back(now->val); | |
now = now->left; | |
} | |
if(!st.empty()) | |
{ | |
now = st.top(); st.pop(); | |
now = now->right; | |
} | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
root->right->left
form to save, and reverse it will be the correct result.