Skip to content

Instantly share code, notes, and snippets.

@pwxcoo
Last active September 12, 2018 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pwxcoo/7cff67a84601ea7c79dfe49717c3fc85 to your computer and use it in GitHub Desktop.
Save pwxcoo/7cff67a84601ea7c79dfe49717c3fc85 to your computer and use it in GitHub Desktop.
Binary Tree Traversal of Iteration (non-recursion)
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;
}
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;
}
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;
}
@pwxcoo
Copy link
Author

pwxcoo commented Sep 12, 2018

  • another postorder traversal, using root->right->left form to save, and reverse it will be the correct result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment