二叉搜索树的最近公共祖先
题目描述
给定一棵二叉搜索树的先序遍历序列,要求你找出任意两结点的最近公共祖先结点(简称 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;
}