PAT a1143

目的:找到两个节点的最低祖先。在二叉搜索树上找

输入:

M  被测试的节点对数 1000

N  二叉搜索树的节点个数 10000

然后给出二叉搜索树的先序遍历序列

然后再是M个节点对。每对节点有U,V两个节点。

输出:

如果找到了LCA,输出"LCA of U and V is A."

如果LCA是U和V中的一个,输出"X is an ancestor of Y."

如股票没有找到:

可能是因为点不在树中;

输出:ERROR: U is not found. 

           ERROR: V is not found. 

           ERROR: U and V are not found.

算法:

根据二叉搜索树的特点,若是两个节点的最小根节点。那么这个节点的值一定处于两个之间,而且,一定在两个节点之前。

判断在不在树中,用一个map存一下,查找看在不在。

#include<stdio.h>
#include<map>
#include<math.h>

using namespace std;

const int maxn = 10010;
int a[maxn];
map<int,int> b;
int n,m;



int main()
{
    scanf("%d%d",&m,&n);

    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
        b[a[i]] = 1;
    }
    for(int i=0;i<m;i++)
    {
        int u,v;
        scanf("%d%d",&u,&v);
        if(b.find(u)==b.end()&&b.find(v)==b.end())
        {
            printf("ERROR: %d and %d are not found.\n",u,v);
        }else if(b.find(u)==b.end())
        {
            printf("ERROR: %d is not found.\n",u);
        }else if(b.find(v)==b.end())
        {
            printf("ERROR: %d is not found.\n",v);
        }else
        {
            int ans;
            for(int j=0;j<n;j++)
            {
                if(a[j]>min(u,v)&&a[j]<=max(u,v))
                {
                    ans = a[j];
                    break;
                }
            }
            if(ans==u||ans==v)
            {
                printf("%d is an ancestor of %d.\n",ans,ans==u?v:u);
            }else
            {
                printf("LCA of %d and %d is %d.\n",u,v,ans);
            }
        }
    }
    return 0;
}

反思:最后一些困难,是狭隘得理解了根节点一定在中间,所以我认为,根节点一定大于左边节点,小于等于右边节点,事实上,这两个节点中可能有根节点,所以两边都有等于。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值