Tuesday, September 2, 2014
Binary Tree Traversal without Recursion 1
vector<int> preorderTraversal(TreeNode *root) {
stack<TreeNode*> st;
vector<int> ret;
if (root==NULL)
return ret;
TreeNode *r = root;
while(r!=NULL||!st.empty())
{
while (r!=NULL)
{
st.push(r);
ret.push_back(r->val);
r=r->left;
}
r = st.top();
st.pop();
r=r->right;
}
return ret;
}
vector<int> inorderTraversal(TreeNode *root) {
stack<TreeNode *> st;
vector<int> ret;
if (root==NULL)
return ret;
TreeNode *r = root;
while(r||!st.empty())
{
while(r)
{
st.push(r);
r = r->left;
}
TreeNode *tmp = st.top();
st.pop();
ret.push_back(tmp->val);
r = tmp->right;
}
return ret;
}
vector<int> postorderTraversal(TreeNode *root) {
vector<int> ret;
if (root==NULL)
return ret;
stack<TreeNode *> st;
TreeNode *r = root;
TreeNode *lastVisitedNode=NULL;
while(!st.empty()||r)
{
while(r)
{
st.push(r);
r=r->left;
}
TreeNode *tmp = st.top();
if (lastVisitedNode!=tmp->right&&tmp->right)
r=tmp->right;
else
{
st.pop();
ret.push_back(tmp->val);
lastVisitedNode = tmp;
}
}
return ret;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment