#include <stdio.h>
#include <stdlib.h>
#define MaxSize 50
typedef struct BiTNode{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct{
BiTree ptr;
int tag; //=0表示左子女被访问,=1表示右子女被访问
}stack;
BiTree CreateBiTree( ){
char ch;
scanf("%c",&ch);
if(ch=='#') return NULL;
else{
BiTree T = (BiTree)malloc(sizeof(BiTNode));
T -> lchild = T -> rchild = NULL;
T->data = ch;
T->lchild = CreateBiTree();
T->rchild = CreateBiTree();
return T;
}
}
void Search(BiTree T , char ch){
stack s[MaxSize];
int top = -1 ;
while( T!=NULL || top!=-1 ){
while ( T!=NULL && T->data!=ch){
s[++top].ptr = T;
s[top].tag = 0;
T = T->lchild;
}
if( T!=NULL && T->data==ch ){
printf("该节点的所有祖先为:\n");
for(int i = 0 ; i <= top ; i ++){
printf( "%c",s[i].ptr->data );
}
exit(1);
}
while( top!=-1 && s[top].tag==1){
top--; //左右孩子都访问过,指针减1
}
if(top!=-1){ //如果左子树全部入栈,指针减1,访问右子树
s[top].tag = 1;
T = s[top].ptr->rchild;
}
}
}
int main()
{
char ch ;
printf("输入各节点:\n");
BiTree T= CreateBiTree();
printf("输入要查找的结点祖先:\n");
scanf("%c",&ch);
scanf("%c",&ch);
Search(T,ch);
}
输出节点祖先(后序遍历顺序栈)
猜你喜欢
转载自blog.csdn.net/RRWJ__/article/details/83388352
今日推荐
周排行