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
Here is the right code which is a modification of your code. Just look-up the changes
void preorder(node* r1)
{stack<node*> st;
st.push(r1);
node* root;
root=r1;
cout<<root->val<<" ";
while(!st.empty())
{if(root->left!=NULL)
{st.push(root->left);
cout<<st.top()->val<<" ";
root=root->left;
}
else{root=st.top();
st.pop();
if(root->right!=NULL)
{st.push(root->right);
cout<<st.top()->val<<" ";
root=root->right;
}
else
root->left=NULL;
}
}
}
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.
Pre-order Traversal
Initialization: Push Root node onto the Stack
While(Stack not Emtpy)
{
Node = Stack.pop();
print Node;
Push Node->right onto the Stack (pushing first, as I need to process left tree first.
Stack is LIFO)
Push Node->left onto the Stack
}
The above pseudocode should print Pre-order traversal.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.