查找一个二叉树的所有祖先问题
/*调不出来*/
#define MAXSIZE 256
#include<stdio.h>
typedef struct bnode{
char data;
struct bnode *lchild,*rchild;
}Bnode,*BTree;/*定义二叉树*/
typedef struct{
BTree node;
int flag;
}DataType;
typedef struct{
DataType data[MAXSIZE];
int top;
}SeqStack,*PSeqStack;/*栈的定义*/
PSeqStack Init_SeqStack(void)
{
PSeqStack S;
S=(PSeqStack)malloc(sizeof(SeqStack));
if(S)
S->top=-1;
return S;
}
int Empty_SeqStack(PSeqStack S)
{
if(S->top==-1)
return 1;
else return 0;
}
int Push_SeqStack(PSeqStack S,DataType x)/*入栈*/
{
if(S->top==MAXSIZE-1)
return 0;
else
{
S->top++;
S->data[S->top]=x;
return 1;
}
}
int Pop_SeqStack(PSeqStack S,DataType *x)/*出栈*/
{
if(Empty_SeqStack(S))
return 0;
else
{
*x=S->data[S->top];
S->top--;
return 1;
}
}
BTree CreatTree(void)/*建立二叉树*/
{
BTree t;
char ch;
ch=getchar();
if(ch==' ') t=NULL;
else
{
t=(BTree)malloc(sizeof(Bnode));
t->data=ch;
t->lchild=CreatTree();
t->rchild=CreatTree();
}
return t;
}
void PostOrder(BTree t,char x)/*查找X的祖先*/
{
PSeqStack S;
DataType Sq;
BTree p=t;
int found=0;
S=Init_SeqStack();
while(p||!Empty_SeqStack(S))
{
if(p)
{
Sq.flag=0;
Sq.node=p;
Push_SeqStack(S,Sq);
p=p->lchild;
}
else
{
Pop_SeqStack(S,&Sq);
p=Sq.node;
if(Sq.flag==0)
{
Sq.flag=1;
Push_SeqStack(S,Sq);/*再次入栈*/
p=p->rchild;
}
else
{
if(p->data==x)/*找到x*/
{
found=1;
break;
}
}
}
}
if(found)
{
while(!Empty_SeqStack(S))
{
Pop_SeqStack(S,&Sq);
printf("%c",(Sq.node)->data);
}
}
else
printf("The value is not found in the tree!\n");
}
int main()
{
char x;
BTree t;
printf("input a tree:\nexample:ab c \n");
t=CreatTree();
printf("input your seaching element:\n");
scanf("%c",&x);
PostOrder(t,x);
getch();
}