查找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;
}

 

转载于:https://www.cnblogs.com/Ycourage/p/10066131.html

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值