#include <iostream>
#include <string>
using namespace std;
struct BiNode{
char ch;
BiNode * Left;
BiNode * Right;
};
BiNode * root=NULL;
void Create(BiNode * & root)
{
char ch;
cin>>ch;
if(ch=='#')
{
root=NULL;return;
}
root=new BiNode;
root->ch=ch;
Create(root->Left);
Create(root->Right);
}
void FindParent(BiNode * & result,BiNode * root,BiNode * pre,char son)
{
if(root==NULL)
return;
if(root->ch==son)
{
result=pre;return;
}
if(!result)
FindParent(result,root->Left,root,son);
if(!result)
FindParent(result,root->Right,root,son);
}
void main()
{
Create(root);
BiNode * result=NULL;
FindParent(result,root,NULL,'A');
cout<<"Parent: "<<result->ch;
::system("pause");
#include <string>
using namespace std;
struct BiNode{
char ch;
BiNode * Left;
BiNode * Right;
};
BiNode * root=NULL;
void Create(BiNode * & root)
{
char ch;
cin>>ch;
if(ch=='#')
{
root=NULL;return;
}
root=new BiNode;
root->ch=ch;
Create(root->Left);
Create(root->Right);
}
void FindParent(BiNode * & result,BiNode * root,BiNode * pre,char son)
{
if(root==NULL)
return;
if(root->ch==son)
{
result=pre;return;
}
if(!result)
FindParent(result,root->Left,root,son);
if(!result)
FindParent(result,root->Right,root,son);
}
void main()
{
Create(root);
BiNode * result=NULL;
FindParent(result,root,NULL,'A');
cout<<"Parent: "<<result->ch;
::system("pause");
}
测试输入:BC##DEA##F##G##
输出:Parent: E