/* * @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; }