Rec11 2020-11-04 02:46 采纳率: 0%
浏览 184

怎么输入要创建的二叉树?

#define null 0

include

include

include

#include
#include
using namespace std;

typedef struct BIThrNODE{
int data ;
int lflag ,rflag;
struct BIThrNODE *lchild ,*rchild;
}BiThrTree,*bitree;
void creatBiThrTree(BiThrTree *&t)
{ int x = 0 ;

scanf("%d",&x);
if(x==0)
{
t= null;

}
else
{
t = (BiThrTree*)malloc(sizeof(BiThrTree));
t->data = x;
t->rflag = 0;
t->lflag = 0;
creatBiThrTree(t->lchild);
creatBiThrTree(t->rchild);
}
}
BiThrTree *pre = null;

void InThreading(BiThrTree * p)
{
stackst;
do{
while(p!=null){st.push(p);p=p->lchild;}
p=st.top();st.pop();
if(pre!=null)
{if(pre->rchild==null){pre->rchild=p;pre->rflag=1;}
if(p->lchild==null){p->lchild=pre;p->lflag=1;}
}
pre=p;p=p->rchild;
}while(!st.empty()||p!=null);
}

void InOrderThreading(BiThrTree *t,BiThrTree *&Thrt)
{

Thrt =(BiThrTree *)malloc(sizeof(BiThrTree));
Thrt->lflag = 1 ;
Thrt->rflag = 0 ;
if(!t)
Thrt->lchild = Thrt ;
else
{
Thrt->lchild = t ;
pre = Thrt ;
InThreading(t);
Thrt ->rchild =pre ;
pre->rchild =Thrt ;

}
}

void InOrderTraverse_Thr(BiThrTree *Thrt)
{

BiThrTree * p =Thrt->lchild;

while(p != Thrt )
{
while(p->lflag == 0)
{

p = p->lchild;

}

if(p->lflag)
printf("%d,",p->data);
while((p->rflag == 1)&&(p->rchild != Thrt))
{
p = p->rchild ;

  printf("%d,",p->data);

}

p = p->rchild ;
}
}

main()
{ BiThrTree *t,*Thrt;
printf("请输入要创建的二叉树:");
creatBiThrTree(t);
InOrderThreading(t,Thrt);
printf("遍历二叉树结果为:");
InOrderTraverse_Thr(Thrt);
printf("\n");
}

展开全部

  • 写回答

1条回答 默认 最新

  • threenewbee 2020-11-04 03:45
    关注

    按照你的代码,输入一些数字,代表前序遍历二叉树,0表示是叶子节点,比如说

    1

    23

    4567

    那么就输入

    1 2 4 0 0 5 0 0 3 6 0 0 7 0 0 

    评论
    编辑
    预览

    报告相同问题?

    手机看
    程序员都在用的中文IT技术交流社区

    程序员都在用的中文IT技术交流社区

    专业的中文 IT 技术社区,与千万技术人共成长

    专业的中文 IT 技术社区,与千万技术人共成长

    关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

    关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

    客服 返回
    顶部