二叉搜索树的最近公共祖先【数据结构】

二叉搜索树的最近公共祖先

题目描述
给定一棵二叉搜索树的先序遍历序列,要求你找出任意两结点的最近公共祖先结点(简称 LCA)。

输入
输入的第一行给出两个正整数:待查询的结点对数 M(≤ 1 000)和二叉搜索树中结点个数 N(≤ 10 000)。随后一行给出 N 个不同的整数,为二叉搜索树的先序遍历序列。最后 M 行,每行给出一对整数键值 U 和 V。所有键值都在整型int范围内。

输出
对每一对给定的 U 和 V,如果找到 A 是它们的最近公共祖先结点的键值,则在一行中输出 LCA of U and V is A.。但如果 U 和 V 中的一个结点是另一个结点的祖先,则在一行中输出 X is an ancestor of Y.,其中 X 是那个祖先结点的键值,Y 是另一个键值。如果 二叉搜索树中找不到以 U 或 V 为键值的结点,则输出 ERROR: U is not found. 或者 ERROR: V is not found.,或者 ERROR: U and V are not found.。

输入样例1
6 8
6 3 1 2 5 4 8 7
2 5
8 7
1 9
12 -3
0 8
99 99

输出样例1
LCA of 2 and 5 is 3.
8 is an ancestor of 7.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.

二叉搜索树性质

对于二叉搜索树,我们规定任一结点的左子树仅包含严格小于该结点的键值,而其右子树包含大于或等于该结点的键值。如果我们交换每个节点的左子树和右子树,得到的树叫做镜像二叉搜索树。

#include<bits/stdc++.h>
using namespace std;
//树节点
struct tree
{
    int value;
    tree* left=NULL;
    tree* right=NULL;
};
//该节点是否存在
bool exist[10005];
int a[10005];
//插入节点建树
//要利用二叉搜索树的性质
tree* insert(int begin,int end)
{
    if(begin>end) return NULL;
    int rootValue=a[begin];
    tree* root=new tree;
    root->value=rootValue;
    //第一个比rootValue大的到结尾为右子树
    int i;
    for(i=begin+1;i<=end;i++)
    {
        if(a[i]>rootValue) break;
    }
    //递归
    root->left=insert(begin+1,i-1);
    root->right=insert(i,end);
    return root;
}
//找公共祖先节点LCA
int findpar(int u,int v,tree* root)
{
    while(1)
    {
        if(root->value>u&&root->value>v) root=root->left;
        else if(root->value<u&&root->value<v) root=root->right;
        else break;
    }
    return root->value;
}
int main()
{
    int m,n;
    cin>>m>>n;
    //根节点
    tree* root=NULL;
    for(int i=0;i<n;i++)
    {
        cin>>a[i];
        exist[a[i]]=1;
    }
    root=insert(0,n-1);
    for(int i=0;i<m;i++)
    {
        int u,v;
        cin>>u>>v;
        //两个节点都不存在
        if(!exist[u]&&!exist[v])
        {
            cout<<"ERROR: "<<u<<" and "<<v<<" are not found."<<endl;
            continue;
        }
        //一个节点不存在
        if(!exist[u])
        {
            cout<<"ERROR: "<<u<<" is not found."<<endl;
            continue;
        }
        if(!exist[v])
        {
            cout<<"ERROR: "<<v<<" is not found."<<endl;
            continue;
        }
        //两个节点都存在
        bool flag=0;
        if(findpar(u,v,root)==u) cout<<u<<" is an ancestor of "<<v<<"."<<endl;
        else if(findpar(u,v,root)==v) cout<<v<<" is an ancestor of "<<u<<"."<<endl;
        else cout<<"LCA of "<<u<<" and "<<v<<" is "<<findpar(u,v,root)<<"."<<endl;
    }
    return 0;
}
  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值