查找x节点的所有祖先并输出 递归

递归写法没有基于后续遍历的非递归写法快,但是简短吖。先记录下

基本思路是:一个节点如果有x这个子孙,那么它就是x的祖先,输出就可以。

#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
const int maxsize=1e3;

typedef struct BiTNode
{
    char data;
    struct BiTNode *lson,*rson;
} BiTNode,*BiTree;

void Creat_BiTree(BiTree &t)
{
    char ch=getchar();
    if(ch=='\n')
        return;
    if(ch=='*')
        t=NULL;
    else {
        t=new BiTNode;
        t->data=ch;
        Creat_BiTree(t->lson);
        Creat_BiTree(t->rson);
    }
}

bool flag;
bool Find_ancestors(BiTree t,char x)
{
    if(t==NULL)
        return false;
    if(t->data==x) {
        flag=true;
        return true;
    }
    if(Find_ancestors(t->lson,x)||Find_ancestors(t->rson,x)) {
        cout<<t->data<<" ";
        return true;
    }
    return false;
}

int main()
{
    BiTree t;
    Creat_BiTree(t);
    char x;
    cin>>x;
    if(t->data==x)
        cout<<"没有祖先节点"<<endl;
    else {
        flag=false;
        Find_ancestors(t,x);
        if(!flag)
            cout<<"x不存在"<<endl;
    }
    return 0;
}

 

posted @ 2018-12-04 19:07  yooonn  阅读(1902)  评论(0编辑  收藏  举报