Problem Description
有一棵二叉树,其结点值为字符型并假设各值互不相等,采用二叉链表存储。现输入其扩展二叉树的前序遍历序列,建立该二叉树,要求在该二叉树中查找字符值为x的结点,找到x时,输出x的相关信息,没找到x则输出"not find"。
Input
第一行为一个整数n,表示以下有n组数据,每组数据占两行,每组第一行表示扩展二叉树的前序遍历序列;第二行表示待查找的字符x。
Output
若查找成功,先输出该结点的双亲值,再输出其左右孩子值:(左孩子,右孩子),若其双亲或者孩子值为空输出#;查找失败输出“not find”。
Sample Input
4 AB#D##C## A AB#D##C## B AB#D##C## D AB#D##C## G
Sample Output
#(B,C) A(#,D) B(#,#) not find
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
typedef struct BiNode {
char data;
struct BiNode* lchild,*rchild;
} BiNode,*BiTree;
class Tree {
public:
Tree() {
root=Creat();
temp=NULL;
p=NULL;
rtemp=ltemp='#';
fine=false;
}
~Tree() {
Release(root);
}
void preorder() {
preorder(root);
}
bool Find(char ch) {
Find(root,ch);
return fine;
}
void Parent(char ch) {
Parent(root,p,ch);
if(!temp) {
cout<<"#";
} else {
cout<<temp->data;
}
}
void Children(char ch) {
Children(root,ch);
cout<<"("<<ltemp<<","<<rtemp<<")"<<endl;
}
private:
BiTree root;
bool fine;
void Find(BiTree root,char ch) {
if(root) {
if(root->data==ch) {
fine=true;
} else {
Find(root->lchild,ch);
Find(root->rchild,ch);
}
}
}
void Release(BiTree t) {
if(t) {
Release(t->lchild);
Release(t->rchild);
delete t;
}
}
void preorder(BiTree root) {
if(root) {
cout<<root->data;
preorder(root->lchild);
preorder(root->rchild);
}
}
BiTree Creat() {
BiTree bt;
char ch;
cin>>ch;
if(ch=='#') {
bt=NULL;
} else {
bt=new BiNode;
bt->data=ch;
bt->lchild=Creat();
bt->rchild=Creat();
}
return bt;
}
BiTree temp;
BiTree p;
void Parent(BiTree root,BiTree p,char ch) {
if(root) {
if(root->data==ch) {
temp=p;
}
Parent(root->lchild,root,ch);
Parent(root->rchild,root,ch);
}
}
char rtemp,ltemp;
void Children(BiTree root,char ch) {
if(root) {
if(ch==root->data) {
if(root->lchild)
ltemp=root->lchild->data;
if(root->rchild)
rtemp=root->rchild->data;
}
Children(root->lchild,ch);
Children(root->rchild,ch);
}
}
};
int main() {
int n;
while(cin>>n) {
while(n--) {
Tree t;
char ch;
cin>>ch;
if(t.Find(ch)) {
t.Parent(ch);
t.Children(ch);
} else {
cout<<"not find"<<endl;
}
}
}
return 0;
}