队列??你每输入一个节点将其存入队列中,再输入它的左孩子,它的左孩子也会入队,我们取的时候应先取该节点的左孩子,
LZ一定要用队列也行,但绝对不是正确的选择!
队列如下:
#include
using namespace std;
typedef struct bitnode
{
聽聽聽聽char data;
聽聽聽聽struct bitnode *lchild,*rchild;
}*bitree,tree;
int number=0;
void createbitree(bitree &t)
{
聽聽聽聽char c;
聽聽聽聽int i=0,r=0,f=0;//r,f分别指向队首和队尾
聽聽聽聽bitree p=NULL,temp=NULL,pre=NULL,s[100];
聽聽聽聽s[0]=NULL;
聽聽聽聽int lflag[100]={0};
聽聽聽聽int rflag[100]={0};
聽聽聽聽printf("请输入根节点:");
聽聽聽聽t=new tree;
聽聽聽聽t->lchild=t->rchild=NULL;
聽聽聽聽scanf("%c",&t->data);
聽聽聽聽temp=pre=t->lchild;
聽聽聽聽s[++i]=t;
聽聽聽聽f=i;
聽聽聽聽p = t;
聽聽聽聽while(f!=r)
聽聽聽聽{
聽聽聽聽聽聽聽聽if(p->lchild==NULL&&lflag==0)
聽聽聽聽聽聽聽聽{
聽聽聽聽聽聽聽聽聽聽聽聽printf("请输入%c的左孩子:",p->data);
聽聽聽聽聽聽聽聽聽聽聽聽fflush(stdin);
聽聽聽聽聽聽聽聽聽聽聽聽scanf("%c",&c);
聽聽聽聽聽聽聽聽聽聽聽聽if(c!='#')
聽聽聽聽聽聽聽聽聽聽聽聽{
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p->lchild = new tree;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p = p->lchild;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p->lchild=p->rchild=NULL;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p->data = c;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽s[++f]=p;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽i = f;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽lflag=rflag=0;
聽聽聽聽聽聽聽聽聽聽聽聽}
聽聽聽聽聽聽聽聽聽聽聽聽else
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽lflag=1;
聽聽聽聽聽聽聽聽}
聽聽聽聽聽聽聽聽else if(p->rchild==NULL&&rflag==0)
聽聽聽聽聽聽聽聽{
聽聽聽聽聽聽聽聽聽聽聽聽printf("请输入%c的右孩子:",p->data);
聽聽聽聽聽聽聽聽聽聽聽聽fflush(stdin);
聽聽聽聽聽聽聽聽聽聽聽聽scanf("%c",&c);
聽聽聽聽聽聽聽聽聽聽聽聽if(c!='#')
聽聽聽聽聽聽聽聽聽聽聽聽{
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p->rchild = new tree;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p = p->rchild;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p->lchild=p->rchild=NULL;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p->data = c;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽s[++f]=p;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽i=f;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽lflag=rflag=0;
聽聽聽聽聽聽聽聽聽聽聽聽}
聽聽聽聽聽聽聽聽聽聽聽聽else
聽聽聽聽聽聽聽聽聽聽聽聽{
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽rflag=1;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p=s[++r];
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽i=r;
聽聽聽聽聽聽聽聽聽聽聽聽}
聽聽聽聽聽聽聽聽}
聽聽聽聽聽聽聽聽else
聽聽聽聽聽聽聽聽{
聽聽聽聽聽聽聽聽聽聽聽聽p=s[++r];
聽聽聽聽聽聽聽聽聽聽聽聽i=r;
聽聽聽聽聽聽聽聽}
聽聽聽聽}
}
void preorder(bitree &t)//遍历二叉树,输出函数
{
聽聽聽聽if (t!=0)
聽聽聽聽{
聽聽聽聽聽聽聽聽coutdata);
聽聽聽聽temp=pre=t->lchild;
聽聽聽聽s[++i]=t;
聽聽聽聽p = t;
聽聽聽聽while(s!=NULL)
聽聽聽聽{
聽聽聽聽聽聽聽聽if(p->lchild==NULL&&lflag==0)
聽聽聽聽聽聽聽聽{
聽聽聽聽聽聽聽聽聽聽聽聽printf("请输入%c的左孩子:",p->data);
聽聽聽聽聽聽聽聽聽聽聽聽fflush(stdin);
聽聽聽聽聽聽聽聽聽聽聽聽scanf("%c",&c);
聽聽聽聽聽聽聽聽聽聽聽聽if(c!='#')
聽聽聽聽聽聽聽聽聽聽聽聽{
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p->lchild = new tree;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p = p->lchild;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p->lchild=p->rchild=NULL;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p->data = c;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽s[++i]=p;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽lflag=rflag=0;
聽聽聽聽聽聽聽聽聽聽聽聽}
聽聽聽聽聽聽聽聽聽聽聽聽else
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽lflag=1;
聽聽聽聽聽聽聽聽}
聽聽聽聽聽聽聽聽else if(p->rchild==NULL&&rflag==0)
聽聽聽聽聽聽聽聽{
聽聽聽聽聽聽聽聽聽聽聽聽printf("请输入%c的右孩子:",p->data);
聽聽聽聽聽聽聽聽聽聽聽聽fflush(stdin);
聽聽聽聽聽聽聽聽聽聽聽聽scanf("%c",&c);
聽聽聽聽聽聽聽聽聽聽聽聽if(c!='#')
聽聽聽聽聽聽聽聽聽聽聽聽{
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p->rchild = new tree;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p = p->rchild;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p->lchild=p->rchild=NULL;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p->data = c;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽s[++i]=p;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽lflag=rflag=0;
聽聽聽聽聽聽聽聽聽聽聽聽}
聽聽聽聽聽聽聽聽聽聽聽聽else
聽聽聽聽聽聽聽聽聽聽聽聽{
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽rflag=1;
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽p=s[--i];
聽聽聽聽聽聽聽聽聽聽聽聽}
聽聽聽聽聽聽聽聽}
聽聽聽聽聽聽聽聽else
聽聽聽聽聽聽聽聽聽聽聽聽p=s[--i];
聽聽聽聽}
}
void preorder(bitree &t)//遍历二叉树,输出函数
{
聽聽聽聽if (t!=0)
聽聽聽聽{
聽聽聽聽聽聽聽聽cout |