[数据结构]二叉树中求结点的祖先

在二叉链表表示的二叉树中(值域为字符型),查找值为x的结点的所有祖先结点并输出。
输入说明:
利用二叉树的先序递归创建二叉树,键盘输入字符序列,@代表空结点,中间不允许有重复的值,建立二叉树,接着输入字符x。
 

[数据结构]二叉树中求结点的祖先_第1张图片


输出说明:
(1)若x为根,输出:No ancestor nodes。
(2)若x不存在,则输出:no nodes;
(3)否则,依次输出x的祖先结点,从离x最近的父节点开始,输出到根节点,数据之间用一个空格分隔。

输入格式:

ABD@@FE@@@CG@H@@I@@
E

输出格式:

FBA

输入样例:

在这里给出一组输入。例如:

ABD@@FE@@@CG@H@@I@@
E

输出样例:

在这里给出相应的输出。例如:

FBA
#include 
using namespace std;
typedef char ElemType;
 typedef struct BiNode
{
     ElemType data;
    struct BiNode *lchild,*rchild;
}BiNode,*BiTree;
typedef struct
{
    int tag;
    BiTree t;
}st;
void Create(BiTree &T)
{
    char ch;
    cin>>ch;
        if(ch=='@')T=NULL;
        else
        {
            T = new BiNode;
            T->data=ch;
            Create(T->lchild);
            Create(T->rchild);
    }
}
void fun1(st s[],int n)//输出祖先节点
{
    for(int i=n-1;i>0;i--)
        printf("%c",s[i].t->data);
}
void FIND(BiTree T,char ch)//后序遍历改进
{
    st s[100];
    int i=0,k=0;
    BiTree p;
    if(T==NULL)return;
    if(T->data==ch){
        printf("No ancestor nodes\n");return;
    }
    p=T;
    while(i>=0)
    {
        while(p!=NULL)
        {
            i++;s[i].t=p;s[i].tag=0;p=p->lchild;
        }
        if(i>0)
        {
            p=s[i].t->rchild;s[i].tag=1;
        }
        if(p==NULL)
        while(s[i].tag==1)
        {
            //cout<data;//后序遍历输出改判断
            if(s[i].t->data==ch){fun1(s,i);k=1;}
            i--;
        }
        if(i==0)break;
    }
    if(k==0) printf("no nodes\n");
}

int main()
{
    BiTree T;
    Create(T);
    char ch;
    cin>>ch;
    FIND(T,ch);
}

你可能感兴趣的:(数据结构,c++,算法,数据结构)