习题4.5 顺序存储的二叉树的最近的公共祖先问题 (25分)

习题4.5 顺序存储的二叉树的最近的公共祖先问题 (25分)
这个题目比较有意思,首先我们要知道顺序存储的二叉树的特性,那就是他的根节点是在i/2这个位置的,那么这个题我们就只需要写一个函数,每次将大的树除以2便可以了,最终找到根节点。如果为空的话,特判一下就ok了。

#include <cstdio>
using namespace std;
int k;
int findroot(int a[],int x,int y)
{
    while(1)
    {
        if(x>y)
        {
            x/=2;
        }
        else
        {
            y/=2;
        }
        if(x==y)
        {
            k=x;
            return a[x];
        }
    }
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        k=-1;
        int a[1010];
        for(int i=1; i<=n; i++)
            scanf("%d",&a[i]);
        int x,y;
        scanf("%d %d",&x,&y);
        int ans=findroot(a,x,y);
        if(x==y)
        {
            printf("%d %d\n",x,a[x]);
        }
        else if(a[x]==0)
        {
            printf("ERROR: T[%d] is NULL\n",x);
        }
        else if(a[y]==0)
        {
            printf("ERROR: T[%d] is NULL\n",y);
        }
        else
        {
            printf("%d %d\n",k,ans);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值