7-14 二叉搜索树的最近公共祖先 (30 分)

这道题目我认为只有这一种做法是nlogn的复杂度,,,,来记录一下,别的方法(一个一个插入的那种)对于深度很深的情况都是会把时间拖到n方的时间复杂度。这种做法建树过程中只有排序的时间最长;建树是n的时间复杂度(每一个节点遍历一次)。

#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#define PII pair<double, int>
typedef long long ll;
using namespace std;
const int maxn = (1<<10)+100;
struct node
{
    int data;
    struct node *l,*r;
};
int pre[110000];
int ino[110000];
struct node *creat(int n,int *pre,int *ino)
{
//    cout<<n<<endl;
    if(n<1) return NULL;
    struct node *it = new node;
    it->data=pre[0];
    it->l=it->r=NULL;
    int i;
    for(i=0;i<n;i++)
    {
        if(pre[0]==ino[i])
        {
            break;
        }
    }
    it->l=creat(i,pre+1,ino);
    it->r=creat(n-i-1,pre+i+1,ino+i+1);
    return it;
}

map<int,bool> ma;
int zuihou=-1;
void find(struct node *it,int x,int y)
{
    if(it==NULL)return ;
    if(it->data>=x&&it->data<=y)
    {
        zuihou=it->data;
        return ;
    }
    if(it->data>y)
    find(it->l,x,y);
    if(it->data<x)
    find(it->r,x,y);
}
int main()
{
    int n,m;
    cin>>m>>n;
    struct node *root;
    root=NULL;
    for(int i=0;i<n;i++)
    {
        cin>>pre[i];
        ino[i]=pre[i];
        ma[ino[i]]=true;
    }
    sort(ino,ino+n);
    root=creat(n,pre,ino);
    while(m--)
    {
        int x,y;
        cin>>x>>y;
        if(!ma[x]&&!ma[y])
        {
            printf("ERROR: %d and %d are not found.\n",x,y);
            continue;
        }
        if(!ma[x])
        {
            printf("ERROR: %d is not found.\n",x);
            continue;
        }
        if(!ma[y])
        {
             printf("ERROR: %d is not found.\n",y);
            continue;
        }
        // cout<<root->r->data<<endl;
        if(x<y)
        find(root,x,y);
        else find(root,y,x);
        if(x==zuihou)
        {
            printf("%d is an ancestor of %d.\n",zuihou,y);
            continue;
        }
        if(y==zuihou)
        {
            printf("%d is an ancestor of %d.\n",zuihou,x);
            continue;
        }
        printf("LCA of %d and %d is %d.\n",x,y,zuihou);
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值