浙大版《数据结构(第2版)》题目集习题4.5 顺序存储的二叉树的最近的公共祖先问题 (25分)

ok,又水了一道题

#include<stdio.h>
#include<stdlib.h> 
#define max 1001
#define swap(a,b) a ^= b,b ^= a,a ^= b;
typedef struct Tnode *Tree;
struct Tnode{
    int data[max];
    int size=0;
};

int NCA(int p1, int p2){
    while(p1!=p2){
        if(p1>p2) {swap(p1,p2)}//保证p1在p2上 
        while(p2>p1){
        p2/=2; 
        }
    }
    return p1;
}

int main()
{
    int N,k;
    scanf("%d",&N);
    Tree t=(Tree)malloc(sizeof(struct Tnode));
    t->data[0]=0;
    for(t->size=1;t->size<=N;t->size++){
        scanf("%d",&t->data[t->size]);
    }
    t->size--;
    int p1,p2;
    scanf("%d %d",&p1,&p2);
    if(!t->data[p1]) printf("ERROR: T[%d] is NULL",p1);
    else if(!t->data[p2]) printf("ERROR: T[%d] is NULL",p2);
    else{
        printf("%d %d",NCA(p1,p2),t->data[NCA(p1,p2)]);
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值