Here is an iterative version of preorder traversal.The idea is to
push the root into a stack.
If left child is not NULL.Push the left child and root=root->left
Else root=Top of stack;Pop;push its right child and root=root->right
Its working on some trees but for some input trees it prints a duplicate value.The behavior of stack is surprising.How does it change from (4 5 6 8) to (4 6 8)?
void preorder(node* root)
{stack<node*> st;
st.push(root);
cout<<root->val<<" \n ";
while(!st.empty())
{if(root->left!=NULL)
{st.push(root->left);
cout<<st.top()->val<<" ";
// printstack(st);
root=root->left;
}
else{root=st.top();
st.pop();
if(root->right!=NULL)
{st.push(root->right);
cout<<st.top()->val<<" ";
//printstack(st);
root=root->right;
}
}
}
}
Helper function printstack used to debug
void printstack(stack<node*> s)
{stack<node*> t;
t=s;
while(!t.empty())
{cout<<t.top()->val<<" ";
t.pop();
}
}
For this input tree,the printed stack is below.
The preorder output is
8 3 1 6 5 4 4 7 9
______8_ / \ __3_ 9 / \ 1 ___6 / \ 5 7 / 4
3 8
1 3 8
6 8
5 6 8
4 5 6 8
4 6 8 //How is the Top of stack 4??It should have been 5,Stack being ( 5 6 8)
7 8
9
The issue crops up on nodes that have left children but not right. When the node has a right child, that last if block changes the root before the next iteration, but without it, the root doesn’t switch. Then, the next time through, we see a root (which has already been popped of the stack) that has a left child, so it’s left child is pushed on the stack and visited again.
Hope that helps.