码迷,mamicode.com
首页 > 其他好文 > 详细

寻找二叉树双亲结点

时间:2020-02-25 17:33:14      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:typedef   null   void   stream   last   tree   class   pac   out   

/*
 * @Issue:  寻找X结点的双亲结点
 * @Author: 一届书生
 * @LastEditTime: 2020-02-25 16:50:27
 */
#include<iostream>
using namespace std;
#define type char
typedef struct node{
    type data;
    node *lchild,*rchild;
}Tree,*Pnode;

// 构造树[先序遍历:中左右]
void creat(Pnode &tree){
    type c;
    cin>>c;
    if(c==‘#‘)tree=NULL;
    else{
        tree=new Tree;
        tree->data=c;
        creat(tree->lchild);
        creat(tree->rchild);
    }
}

// 寻找X结点的双亲结点
void find(Pnode t,Pnode a){ //寻找a的双亲结点
    if(!t)return;
    if(t->lchild){
        if(t->lchild->data==a->data){
            cout<<t->data<<endl;
            return ;
        }
        find(t->lchild,a);
    }
    if(t->rchild){
        if(t->rchild->data==a->data){
            cout<<t->data<<endl;
            return ;
        }
        find(t->rchild,a);
    }
}

// 后序遍历
void display(Pnode &t1){
    if(t1){
    display(t1->lchild);
    display(t1->rchild);
    cout<<t1->data<<"  ";
    }
}


int main(){
    // 样例:AB#CD##E##F#GH###
    /*
            A
          /           B     F
          \                C      G  
          /  \    /
         D    E  H

    */
    Pnode t,a;
    t=new Tree;
    a=new Tree;
    creat(t);

    display(t);
    cout<<endl;
    
    type x;
    cin>>x;
    a->data=x;
    a->lchild=NULL;
    a->rchild=NULL;

    find(t,a);
    return 0;
}

  

寻找二叉树双亲结点

标签:typedef   null   void   stream   last   tree   class   pac   out   

原文地址:https://www.cnblogs.com/52dxer/p/12362543.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!