二叉搜索树的建树和寻找最近公共祖先(题目给出了BST的前序遍历,而前序遍历升序排列就是BST的中序遍历了)
#include <bits/stdc++.h>
using namespace std;
typedef struct node *Node;
typedef struct node{
int val;
Node l,r;
}node;
Node T;
int M,N;
int pre[10001];
Node buildTree(int s,int e)
{
if(e < s) return NULL;
if(s == e){
Node tnode = (Node)malloc(sizeof(node));
tnode->val = pre[s];
tnode->l = NULL;
tnode->r = NULL;
return tnode;
}
int i = s+1;
while(i<=e && pre[i]<pre[s])
i++;
Node tnode = (Node)malloc(sizeof(node));
tnode->val = pre[s];
tnode->l = buildTree(s+1,i-1);
tnode->r = buildTree(i,e);
return tnode;
}
bool findd(Node tree, int a, int b,int f)
{
if(f == 0){
if(tree == NULL){
printf("ERROR: %d and %d are not found.\n", a, b);
return true;
}
if(a<tree->val && b<tree->val)return findd(tree->l,a,b,0);
else if(a>tree->val && b>tree->val) return findd(tree->r,a,b,0);
else{
bool fda = tree->val == a || findd(tree->l,a,0,1) || findd(tree->r,a,0,1);
bool fdb = tree->val == b || findd(tree->l,b,0,1) || findd(tree->r,b,0,1);
if(fda&&fdb){
if(tree->val == a||tree->val == b)
printf("%d is an ancestor of %d.\n", tree->val == a ? a : b, tree->val == b ? a : b);
else
printf("LCA of %d and %d is %d.\n", a, b, tree->val);
}
else if (fda == false && fdb == false) {
printf("ERROR: %d and %d are not found.\n", a, b);
}
else {
printf("ERROR: %d is not found.\n", fda ? b : a);
}
return true;
}
}
else{
if(tree == NULL) return false;
if(tree->val == a) return true;
if(tree->val > a)return findd(tree->l,a,0,1);
return findd(tree->r,a,0,1);
}
}
int main()
{
cin>>M>>N;
int a,b;
for(int i=0;i<N;i++){
cin>>pre[i];
}
T = buildTree(0,N-1);
for(int i=0;i<M;i++){
cin>>a>>b;
findd(T, a, b, 0);
}
return 0;
}
看到有一种非常巧妙的方法,都不需要建树:
https://www.liuchuo.net/archives/4616
map<int, bool> mp用来标记树中所有出现过的结点,遍历一遍pre数组,将当前结点标记为a,如果u和v分别在a的左、右,或者u、v其中一个就是当前a,即(a >= u && a <= v) || (a >= v && a <= u),说明找到了这个共同最低祖先a,退出当前循环,最后根据要求输出结果即可
#include <iostream>
#include <vector>
#include <map>
using namespace std;
map<int, bool> mp;
int main() {
int m, n, u, v, a;
scanf("%d %d", &m, &n);
vector<int> pre(n);
for (int i = 0; i < n; i++) {
scanf("%d", &pre[i]);
mp[pre[i]] = true;
}
for (int i = 0; i < m; i++) {
scanf("%d %d", &u, &v);
for(int j = 0; j < n; j++) {
a = pre[j];
if ((a >= u && a <= v) || (a >= v && a <= u)) break;
}
if (mp[u] == false && mp[v] == false)
printf("ERROR: %d and %d are not found.\n", u, v);
else if (mp[u] == false || mp[v] == false)
printf("ERROR: %d is not found.\n", mp[u] == false ? u : v);
else if (a == u || a == v)
printf("%d is an ancestor of %d.\n", a, a == u ? v : u);
else
printf("LCA of %d and %d is %d.\n", u, v, a);
}
return 0;
}