1143 Lowest Common Ancestor

本文介绍了一种使用二叉搜索树(BST)实现最近公共祖先(LCA)查找的高效算法。通过预分配节点数组而非动态创建节点,有效避免了超时问题。文章详细展示了插入操作、节点查找及LCA算法的具体实现,并提供了完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题的关键,记住各个节点的树高。另外采用new动态生成新的节点容易超时,采用数组预先分配节约时间。

#include<iostream>

using namespace std;

 

struct Node{

int value;

Node * lchild;

Node* rchild;

Node* root;

int height;

Node(){

value = 0;

lchild=NULL;

rchild=NULL;

height=0;

root=NULL;

}

};

 

Node Buff[10000];

int k = 0;

 

void insertBST(Node* H,int value)

{

if(value<H->value){

if(H->lchild==NULL){

k++;

H->lchild = Buff+k;

H->lchild->value=value;

// H->lchild->lchild=NULL;

// H->lchild->rchild=NULL;

H->lchild->root = H;

H->lchild->height = H->height+1;

// dicts[value] = H->lchild;

}

else{

insertBST(H->lchild,value);

}

}

else{

if(H->rchild==NULL)

{

k++;

H->rchild= Buff+k;

H->rchild->value=value;

// H->rchild->lchild=NULL;

// H->rchild->rchild=NULL;

H->rchild->root = H;

H->rchild->height = H->height+1;

// dicts[value] = H->rchild;

}

else{

insertBST(H->rchild,value);

}

}

}

 

Node * findNode(Node* H,int value)

{

if(H==NULL) return NULL;

if(H->value == value) return H;

if(H->value <=value) return findNode(H->rchild,value);

return findNode(H->lchild,value);

}

 

void LCA(Node* H,int value1,int value2)

{

Node* root1 = findNode(H,value1);

Node* root2 = findNode(H,value2);

// Node* root1=NULL;

// Node *root2=NULL;

// map<int,Node*>::iterator it = dicts.find(value1);

// if(it!=dicts.end()) root1 = it->second;

// it = dicts.find(value2);

// if(it!=dicts.end()) root2 = it->second;

if(root1==NULL && root2 == NULL){

cout<<"ERROR: "<<value1<<" and "<<value2<<" are not found."<<endl;

return;

}

if(root1==NULL){

cout<<"ERROR: "<<value1<<" is not found."<<endl;

return;

}

if(root2==NULL){

cout<<"ERROR: "<<value2<<" is not found."<<endl;

return;

}

while(root1->height>root2->height)

{

root1 = root1->root;

}

while(root2->height>root1->height)

{

root2 = root2->root;

}

while(root1!=root2)

{

root1=root1->root;

root2=root2->root;

}

if(root1->value==value1){

cout<<value1<<" is an ancestor of "<<value2<<"."<<endl;

return;

}

if(root2->value==value2)

{

cout<<value2<<" is an ancestor of "<<value1<<"."<<endl;

return;

}

cout<<"LCA of "<<value1<<" and "<<value2<<" is "<<root1->value<<"."<<endl;

}

 

int main()

{

map<int,Node*> dicts;

int n,m;

cin>>n>>m;

Node* H = Buff;

H->lchild=NULL;

H->rchild=NULL;

for(int i=0;i<m;++i)

{

int value;

cin>>value;

if(i==0)

{

H->value = value;

H->height = 1;

dicts[value] = H;

}

else

{

insertBST(H,value);

}

}

for(int i=0;i<n;++i)

{

int a,b;

cin>>a>>b;

LCA(H,a,b);

}

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值