一、说明
在一行中输出编号为i和j的六个结点最近的公共祖先结点的编号和值
二、代码:
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 1001
typedef int ElementType;
//通过连续三次异或运算转换a与b
#define Swap(a,b) a^=b,b^=a,a^=b;
typedef int ElementType;
/*---------顺序表的定义----------*/
typedef int Position;
typedef struct LNode *PtrToLNode;
struct LNode{
ElementType Data[MAXSIZE];
Position Last;
};
typedef PtrToLNode Tree;
/*---------顺序表的定义结束----------*/
int NCA(int p1,int p2)
{
//当p1==p2时结束,找到公共祖先p1
while(p1!=p2){
//保证p1在p2上面(p1<p2)
if(p1>p2)
Swap(p1,p2);
while(p2>p1)
p2/=2;//p2向上追赶p1
}
return p1;
}
int main()
{
int N;
int p1,p2,p;
Tree T=(Tree)malloc(sizeof(struct LNode));
T->Data [0]=0;
T->Last =0;
printf("请输入结点个数:");
scanf("%d",&N);
printf("请输入%d个结点数据:",N);
for(T->Last =1;T->Last <=N;T->Last ++)
scanf("%d",&T->Data [T->Last ]);
T->Last --;
printf("请输入结点的编号:");
scanf("%d %d",&p1,&p2);
if(!T->Data [p1])//p1的结点为空
printf("ERROR:T[%d] is NULL\n",p1);
else if(!T->Data[p2])//p2的结点为空
printf("ERROR:T[%d] is NULL\n",p2);
else{
p=NCA(p1,p2);
printf("%d %d\n",p,T->Data[p]);
}
return 0;
}
三、运行:
![](https://img-blog.csdnimg.cn/img_convert/0cf34a2c36a6b6e6b98340b455703c86.png)
![](https://img-blog.csdnimg.cn/img_convert/4ac01b4819f5bce0223884dd7fd16b18.png)