1. 题目要求
寻找两个节点的最近公共祖先。
2. 代码
2.1 结构体和函数
typedef struct tree
{
int data;
struct tree *lchild;
struct tree *rchild;
} TREE;
TREE *CreateTree();
TREE *Common(TREE *root, int p, int q);
2.2 主函数
void main()
{
TREE *root=CreateTree();
scanf(两个结点值);
TREE *com=Common(root, p, q);
if(com==NULL)
printf("两个结点不全在此树中\n");
else
printf("公共祖先是结点%d\n", com->data);
}
2.3 寻找公共祖先
TREE *Common(TREE *root, int p, int q)
{
if(root==NULL)
return NULL;
if(root->data==p || root->data==q)
return root;
TREE *left=Common(root->lchild, p, q);
TREE *right=Common(root->rchild, p, q);
if(left!=NULL && right!=NULL)
return root;
if(right!=NULL)
return right;
if(left!=NULL)
return left;
return NULL;
}