#include <stdio.h>
#include <conio.h>
int get=0;
typedef struct tn
{
int Element;
struct tn *Left;
struct tn *Right;
struct tn *Parent;
}TreeNode, *Tree;
Tree CreateTree()
{
Tree T;
char ch=getchar();
/*getch();*/
if(ch=='#')
{
return NULL;
}
else
{
T=(Tree)malloc(sizeof(TreeNode));
T->Element=ch-'0';
T->Left=CreateTree();
T->Right=CreateTree();
}
return T;
}
int Max(int x, int y)
{
return (x>y?x:y);
}
int Height(Tree T)
{
if(T==NULL)
return -1;
else
return 1+Max(Height(T->Left),Height(T->Right));
}
Tree AddHeaderNode(Tree T)
{
Tree T1;
T1= (Tree)malloc(sizeof(TreeNode));
T1->Left=T;
T1->Element=0;
T->Parent=T1;
return T;
}
void GiveParent(Tree T)
{
if(T!=NULL)
{
if(T->Left!=NULL)
T->Left->Parent=T;
/*printf("%dL ",T->Element);*/
GiveParent(T->Left);
if(T->Right!=NULL)
T->Right->Parent=T;
/*printf("%dR ",T->Element); */
GiveParent(T->Right);
}
else
return ;
}
void PrintParent(Tree T)
{
if(T!=NULL)
{
PrintParent(T->Left);
printf("%d ",T->Parent->Element);
PrintParent(T->Right);
}
}
void PrintTree(Tree T)
{
if(T==NULL)
return;
PrintTree(T->Left);
printf("%d ",T->Element);
PrintTree(T->Right);
return;
}
Tree GetSameParent(Tree T1, Tree T2)
{
while(T1->Element!=T2->Element)
{
if(Height(T1)>Height(T2))
T2=T2->Parent;
else if(Height(T1)<Height(T2))
T1=T1->Parent;
else
{
if(T1->Element!=T2->Element)
{
T1=T1->Parent;
T2=T2->Parent;
}
}
}
return T1;
}
Tree Get
void main()
{
Tree T1;
Tree node1, node2;
printf("The expression you are going to test is 521##43###87###/n");
printf("The tested node is 3 and 8/n");
printf("The Result must be like:/n");
printf("The parent is 5/n ");
printf("/n*********************************************/n");
printf("/tNOW YOU COULD START YOUR TRY/n") ;
printf("*********************************************/n/n");
printf("Expression:");
T1= CreateTree();
AddHeaderNode(T1);
/*
getch();*/
GiveParent( T1);
node1=T1->Left->Right->Left;/*3*/
node2=T1->Left->Left; /*1*/
printf("The parent is %d ",(GetSameParent(node1, node2))->Element);
getch();
return;
}