Tuesday, March 20, 2012

Preorder traversal of a binary tree without recursion


void BSTree::preorder()
{
bool done = false;
stack<Node*> st;
Node* curr = root.get();

while(!done)
{
if(curr != NULL)
{
cout<<curr->data<<'\t';
st.push(curr);
curr = curr->left.get();
}
else
{
if(!st.empty())
{
curr = st.top()->right.get();
st.pop();
}
else
done = true;
}

}
}

No comments:

Post a Comment