// 顺序存储的二叉树的最近的公共祖先问题
#include<stdio.h>
#define MAX_TREE_SIZE 101 //二叉树的最大结点数100
//#define Length 7 //depth=3 (pow(2,3)-1)
typedef struct SqTree{
int data[MAX_TREE_SIZE];
}SqTree;
int g_c;
//index根节点从 1开始
void CreateTree(SqTree &tree,int k){
int temp;
int i=0;
tree.data[0]=0;
for(i=1;i<=k;i++){
scanf("%d",&temp);
if(temp==-1){
return;
}
g_c++;
tree.data[i]=temp;
}
}
int* Comm_Ancestor(SqTree T,int i,int j,int comm[]){ //找i j祖先 0代表是空节点
if(T.data[i]!=0&&T.data[j]!=0){
while(i!=j){
if(i>j){
i=i/2;
}
else{
j=j/2;
}
}
comm[0]=T.data[i];
comm[1]=i;
return comm;
}
comm[0]=-1;
return comm;
}
int main(){
int p,q; //p q为所求节点
int i;
int comm[2];
SqTree tree;
scanf("%d",&p);
scanf("%d",&q);
CreateTree(tree,MAX_TREE_SIZE);
for(i=1;i<=g_c;i++){
printf("%d\t",tree.data[i]);
}
Comm_Ancestor(tree,p,q,comm);
printf("\n");
if(comm[0]==-1){
printf("Error");
// printf("%d,%d",comm[0],comm[1]);
}
else{
printf("树上第%d个节点是%d和%d的公共祖先%d",comm[1],p,q,comm[0]);
}
}