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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM