请大家帮我改一下!
题目是实现二叉树的每个结点的祖先
我的这个程序只有输入最左边的结点才会有真确的答案的
#include<iostream.h>
struct bitree
{
int data;
bitree *lchild,*rchild;
};
bitree *createbitree()//构造树
{
bitree *q;
int ch;
cout<<"请输入数据:";
cin>>ch;
if(ch==0)q=NULL;
else
{
q=new(struct bitree);
q->data=ch;
q->lchild=createbitree();
q->rchild=createbitree();
}
return q;
}
void Search(bitree *bt,int x)
{
typedef struct
{
bitree *t;
int tag;
}stack;
stack s[100];
int top,i;
while(bt!=NULL||top>0)
{
top=0;
while(bt!=NULL&&bt->data!=x)
{
s[++top].t=bt;
s[top].tag=0;
bt=bt->lchild;
}
if(bt->data==x)
{
cout<<"所查结点的所有祖先结点的值为:";
for(i=1;i<=top;i++)
cout<<s[i].t->data<<" ";
return;
}
while(top!=0&&s[top].tag==1)top--;
if(top!=0)
{
s[top].tag=1;
bt=s[top].t->rchild;
}
}
}
void main()
{
bitree *bt;
int x;
bt=createbitree();
cout<<"请输入结点x:";
cin>>x;
Search(bt,x);
}