问题的关键,记住各个节点的树高。另外采用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;
}