利用先序递归遍历算法创建二叉树并输出该二叉树中指定结点的双亲结点。约定二叉树结点数据为单个大写英文字符。当接收的数据是字符“#”时表示该结点不需要创建,否则创建该结点。最后再输出创建完成的二叉树中的指定结点的双亲结点。注意输入数据序列中的“#”字符和非“#”字符的序列及个数关系,这会最终决定创建的二叉树的形态。
输入
输入用例分2行输入,第一行接受键盘输入的由大写英文字符和“#”字符构成的一个字符串(用于创建对应的二叉树),第二行为指定的结点数据。
输出
用一行输出该用例对应的二叉树中指定结点的双亲结点。若相应双亲结点不存在则以“#”代替。
样例输入
A##
A
ABC####
B
样例输出
#
A
#include <iostream> #include <stdlib.h> using namespace std; typedef struct tree { char date; tree *left,*right; }Tree; void creat(Tree*&T)//先序遍历创建二叉树 { char str; cin>>str; if(str!='#') { T = (Tree*)malloc(sizeof(Tree)); T->date = str; creat(T->left); creat(T->right); } else { T=NULL; } } void find(Tree *&T,char elem,Tree *t1)//T为孩子结点,t1存储双亲结点 { if(elem ==T->date) { if(t1==NULL) { cout<<"#"; } else { cout<<t1->date; } } if(T->left!=NULL) { find(T->left,elem,T); } if(T->right!=NULL) { find(T->right,elem,T); } } int main() { Tree *T; creat(T); char elem; cin>>elem; find(T,elem,NULL); return 0; }