#include<stdio.h>
#include<stdlib.h>
#include
using namespace std;
int level,t;
char s[56];
typedef int status;
typedef struct BiTNode
{
char data;
struct BiTNode* lchild, *rchild;
}BiTNode, *BiTree;
BiTree creat()
{
BiTNode *root;
scanf("%d", & s[t]);
if(s[++t]==',')
root=NULL;
else
{
root=new BiTNode;
root->data=s[t];
root->lchild=creat();
root->rchild=creat();
}
return root;
/BiTree root = (BiTree)malloc(sizeof(BiTNode));
int x;
scanf("%d", &x);
if(x==-1)
root = NULL;
else
{
root->data = x;
root->lchild = creat();
root->rchild = creat();
}
return root;/
}
void visit(char x,int level)
{
printf("%c 位于第 %d 层\n",x,level);
}
void pre(BiTNode *root,int level)
{
if(root)
{
visit(root->data,level);
pre(root->lchild,level+1);
pre(root->rchild,level+1);
}
}
int anc[10000];
int i=0, tag=0;
int Ancestor(BiTree bt, int x)
{
if(bt==NULL) return 0;
if(bt->data==x) {tag=1;return 1;}
if(Ancestor(bt->lchild,x)||Ancestor(bt->rchild,s[t])) {anc[i++]=bt->data;return 1;}
}
int main()
{
BiTree bt=creat();
//int x;
//scanf("%d",&x);
Ancestor(bt,s[t]);
if(tag==0) printf("No Node!");
else if(bt->data==s[t]) printf("No Ancestor!");
else
{
for(int j=i-1;j>=0;j--)
printf("%d ",anc[j]);
}
scanf("%s",s);
t=-1;
level=1;
BiTNode *root;
root=creat();
pre(root,level);
return 0;
}
可以麻烦你看看我的这个代码段吗,我想输出二叉树结点的祖先以及其结点的所在层数,可以吗