在二叉链表中查找值为x的节点的双亲节点:
#include <iostream>
//writer:yaojinhui
using namespace std;
typedef struct BiTNode
{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
void createBiTree(BiTree &T)
{
char ch;
cin>>ch;
if(ch=='#')
T=NULL;
else
{
T=new BiTNode;
T->data=ch;
createBiTree(T->lchild);
createBiTree(T->rchild);
}
}
void preOrder(BiTree T)
{
if(T)
{
cout<<T->data;
preOrder(T->lchild);
preOrder(T->rchild);
}
}
//递归实现查找双亲结点
BiTree Find_Father(BiTree T,char data)
{
if(T==NULL)
return NULL;
if(T->lchild!= NULL)//当左孩子存在的时候才进行判断,否则程序出错
{
if(T->lchild->data == data)
{
//cout<<"该节点的父结点是"<<T->data<<endl;
// printf("该节点的父结点是:%c",T->data);
return T;
}
}
if(T->rchild != NULL)//如左子树所示
{
if(T->rchild->data == data)
{
//cout<<"该节点的父结点是"<<T->data<<endl;
// printf("该节点的父结点是:%c",T->data);
return T;
}
}
Find_Father(T->lchild,data);
Find_Father(T->rchild,data);
}
int main()
{
BiTree T;
cout<<"先序建立二叉树:"<<endl;
createBiTree(T);
cout<<"建立的二叉树为:"<<endl;
preOrder(T);
cout<<endl;
char ch;
cout<<"请输入要查询的节点:"<<endl;
cin>>ch;
BiTree p;
p=Find_Father(T,ch);
if(p)
{
cout<<"该节点的双亲节点为:"<<p->data<<endl;
}
else
{
cout<<"你搜索的结点为根节点或你搜索的结点在该二叉树中不存在!"<<endl;
}
/*
p=parentBiTree(T,ch);
if(p)
cout<<"该节点的双亲节点为:"<<p->data<<endl;
else
cout<<"输入的链表为空!"<<endl;
*/
return 0;
}