1151 LCA in a Binary Tree(《算法笔记》版)

 受柳神启发,其实不用建树也可以。这是仿照《算法笔记》的代码风格所写。

核心思想:建树后,利用map<int,int> pos保存中序树每个结点对应在数组中的位置,找到根节点就可以判断出其左右子树。

#include <bits/stdc++.h>
using namespace std;

struct node{
    int data;
    vector<int> child;
    node* lchild;
    node* rchild;
    node(int d){
        this->data = d;
        this->lchild = this->rchild = nullptr;
    }
};
int m,n;
vector<int> pre,in;
map<int,int> pos;  //保存中序树每个结点对应的数组下标

node* create(int preL,int preR,int inL,int inR){
    if(preL>preR){
        return nullptr;
    }
    node* root = new node(pre[preL]);
    int k;
    for(k=inL;k<=inR;k++){
        if(in[k]==pre[preL])
            break;
    }
    int numleft = k-inL;
    root->lchild = create(preL+1,preL+numleft,inL,k-1);
    root->rchild = create(preL+numleft+1,preR,k+1,inR);
    return root;
}

void LCA(node* s,int a,int b){
    if(s==nullptr)return;
    int inRoot = pos[s->data];
    int inA = pos[a];
    int inB = pos[b];
    if((inA>inRoot&&inB<inRoot)||(inA<inRoot&&inB>inRoot)) //a、b分别在左右子树
        printf("LCA of %d and %d is %d.\n",a,b,s->data);
    else if(inA<inRoot&&inB<inRoot){  //a、b都在左子树
        LCA(s->lchild,a,b);
    }
    else if(inA>inRoot&&inB>inRoot){  //a、b都在右子树
        LCA(s->rchild,a,b);
    }
    else if(s->data==a){          //a等于此时根结点对应的值,a就是祖先
        printf("%d is an ancestor of %d\n",a,b);
    }
    else if(s->data==b){          //b等于此时根结点对应的值,b就是祖先
        printf("%d is an ancestor of %d\n",b,a);
    }
}

int main(){
    cin>>m>>n;
    pre.resize(n+1);
    in.resize(n+1);
    for(int i=0;i<n;i++){
        cin>>in[i];
        pos[in[i]] = i;
    }
    for(int i=0;i<n;i++){
        cin>>pre[i];
    }
    node* root = create(0,n-1,0,n-1);
    int a,b;
    for(int i=0;i<m;i++){
        cin>>a>>b;
        bool find1 = true;
        bool find2 = true;
        for(int i=0;i<n;i++){
            if(a==in[i])
                find1 = false;
            if(b==in[i])
                find2 = false;
        }
        if(find1&&find2){
            printf("ERROR: %d and %d are not found.\n",a,b);
        }
        else if(find1||find2){
            printf("ERROR: %d and %d are not found.\n",find1?(a,b):(b,a));
        }
        else{
            LCA(root,a,b);
        }
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值