C language binary tree non recursive traversal case analysis
- 2020-04-02 02:45:42
- OfStack
In this paper, an example of C language implementation of binary tree non - recursive traversal method. It is a common technique in data structure and algorithm design. Share with you for your reference. Specific methods are as follows:
First order traversal:
void preOrder(Node *p) //non-recursive
{
if(!p) return;
stack<Node*> s;
Node *t;
s.push(p);
while(!s.empty())
{
t=s.top();
printf("%dn",t->data);
s.pop();
if(t->right) s.push(t->right);
if(t->left) s.push(t->left);
}
}
Middle order traversal:
void inOrder(Node *p)
{
if(!p)
return;
stack< pair<Node*,int> > s;
Node *t;
int unUsed;
s.push(make_pair(p,1));
while(!s.empty())
{
t=s.top().first;
unUsed = s.top().second;
s.pop();
if(unUsed)
{
if(t->right)
s.push( make_pair(t->right,1) );
s.push( make_pair(t,0) );
if(t->left)
s.push( make_pair(t->left,1));
}
else printf("%dn",t->data);
}
}
Sequential traversal:
void postOrder(Node *p)
{
if(!p) return;
stack<pair<Node*,int> > s;
Node *t;
int unUsed;
s.push(make_pair(p,1));
while(!s.empty())
{
t=s.top().first;
unUsed=s.top().second;
s.pop();
if(unUsed)
{
s.push(make_pair(t,0);
if(t->right)
s.push(make_pair(t->right,1));
if(t->left)
s.push(make_pair(t->left,1));
}
else printf("%dn",t->data);
}
}
I hope that this paper is helpful to the learning of C programming algorithm design.