/*20130701_denyz*/
/*二叉树的存储,输入,输出,遍历(DLR,LDR,RDL)*/
/*查找值为x的结点的双亲结点*/
/*建立二叉树的二叉链表*/
#include <stdio.h>
#include <malloc.h>
typedef struct node{
struct node *Lchild,*Rchild;
char data;
}Btree;
Btree *CreatTree()
{
Btree *BT;
char a;
scanf("%c",&a);
if(a==' ')
BT=NULL;
else
{
BT=(Btree *)malloc(sizeof(Btree)); /*DLR method construct the binary tree*/
BT->data=a;
BT->Lchild=CreatTree();//create Left child tree
BT->Rchild=CreatTree();//create Right child tree
}
return BT;/*the first time run the function,BT is the head pointor of the binary tree*/
}
/*DLR sequence*/
void DLR(Btree *BT)
{
if(BT!=NULL)
{
printf("%c ",BT->data);
DLR(BT->Lchild);
DLR(BT->Rchild);
}
}
/*LDR sequence*/
void LDR(Btree *BT)
{
if(BT!=NULL)
{
LDR(BT->Lchild);
printf("%c ",BT->data);
LDR(BT->Rchild);
}
}
/*LRD sequence*/
void LRD(Btree *BT)
{
if(BT!=NULL)
{
LRD(BT->Lchild);
LRD(BT->Rchild);
printf("%c ",BT->data);
}
}
/*查找值为 x 的双亲结点*/
Btree *find(Btree *BT,char X)
{
char ch;
ch=X;
if(BT)
{
if((BT->Lchild!=NULL && BT->Lchild->data==ch) || (BT->Rchild!=NULL && BT->Rchild->data==ch))
{
printf("存在值为%c的结点的孩子结点值为%c",BT->data,ch);
}
if((BT->Lchild!=NULL && BT->Lchild->data!=ch) || (BT->Rchild!=NULL && BT->Rchild->data!=ch))
{
find(BT->Lchild,ch);
find(BT->Rchild,ch);
}
}
}
int main()
{
Btree *BT,*pos,*parent=NULL;
printf("Note:对于广义表为:a(b(d,x),c( ,e))的二叉树,\
\n输入的时候叶子结点的左右结点以空格的形式输入,\n为空的结点也是以空格输入,输入的时候将括号省略\
\nFor Example:abd x c e \n\n");
BT=CreatTree();
printf("DLR\n");
DLR(BT);
printf("\nLDR\n");
LDR(BT);
printf("\nLRD\n");
LRD(BT);
printf("\n");
find(BT,'x');
getch();
return 1;
}