先序,中序,后序遍历的非递归实现(栈)复习
作者:
丶123
,
2021-08-03 15:27:25
,
所有人可见
,
阅读 205
void preorder(node *T)
{
stack<node*> s;
while(T || !s.empty())
{
while(T)
{
printf("%d",T->data);
s.push(T);
T = T->lchild;
}
if(!s.empty())
{
T = s.top();
s.pop();
T = T->rchild;
}
}
}
void inorder(node *T)
{
stack<node*> s;
while(T || !s.empty())
{
while(T)
{
s.push(T);
T = T->lchild;
}
if(!s.empty())
{
T = s.top();
s.pop();
printf("%d",T->data);
T = T->rchild;
}
}
}
void postorder(node *T)
{
stack<node*> s;
while(T || !s.empty())
{
while(T)
{
s.push(T);
T = T->lchild;
}
if(!s.empty())
{
T = s.top();
if(T->rchild && T->rchild->tag != 1)
{
T = T->rchild;
}else
{
printf("%d",T->data);
s.pop();
T->tag = 1; //说明该节点被访问过
T = NULL; //为了不进入循环,设置为NULL,代表以该节点为根节点的树遍历完
}
}
}
}