后序非递归遍历二叉树后序非递归遍历二叉树
//先序建立建立二叉树,后序非递归遍历二叉树
#include
typedefstruct tree
{
int data;
struct tree *lchild,*rchild;
}tree;
voidEpiorder(tree *root)
{
tree *stack[100];
intsi=-1,flag[100]; //si为栈顶位置,-1为空栈 flag数组用于标识stack中元素的左右儿子访问情况
if(!root)
{
printf("空树!\n");
return;
}
st...
后序非递归遍历二叉树
//先序建立建立二叉树,后序非递归遍历二叉树
#include
typedefstruct tree
{
int data;
struct tree *lchild,*rchild;
}tree;
voidEpiorder(tree *root)
{
tree *stack[100];
intsi=-1,flag[100]; //si为栈顶位置,-1为空栈 flag数组用于标识stack中元素的左右儿子访问情况
if(!root)
{
printf("空树!\n");
return;
}
stack[++si]=root; //root存入栈
flag[si]=1; //stack[si]的左儿子已被访问,flag[si]设置为1 root=root->lchild;
//printf("初始化完成!\n");
while(si!=-1)
{
while(root!=NULL)
{
stack[++si]=root;
flag[si]=1;
root=root->lchild;
}
if(stack[si]->rchild==NULL||flag[si]==2) //flag[si]为2或者stacks[si]为空,说明栈顶可以访问
{
printf("%d\t",stack[si]->data);
flag[si]=0;
si--; //退栈
}
else //stack[si]的右儿子未被访问
{
root=stack[si]->rchild;
flag[si]=2; //此时栈顶的右儿子已被访问,flag[si]设置为2
stack[++si]=root; //右儿子入栈
flag[si]=1; //栈顶元素左儿子访问标志设
为1
root=root->lchild;
}
}
}
void PreorderCreate(tree *root) //先序建立二叉树 {
intlflag,rflag;
if(!root)
return;
root->lchild=root->rchild=NULL;
printf("请输入节点值和子树标志:");
scanf("%d%d%d",&(root->data),&lflag,&rflag); if(lflag!=0) //lflag不为0创建左儿子
root->lchild=(tree*)malloc(sizeof(tree));
if(rflag!=0) //rflag不为0创建右儿子 root->rchild=(tree*)malloc(sizeof(tree));
PreorderCreate(root->lchild);
PreorderCreate(root->rchild);
}
void main()
{
tree *root=(tree*)malloc(sizeof(tree));
PreorderCreate(root);
printf("创建已完成\n");
Epiorder(root);
}
本文档为【后序非递归遍历二叉树】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑,
图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。