Files
Data-Structure/模板//LCA最近共同祖先.cpp
2025-12-16 20:36:27 +08:00

51 lines
1.2 KiB
C++

#include <iostream>
#include <vector>
using namespace std;
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int _val): val(_val), left(nullptr), right(nullptr) {}
};
TreeNode* buildTree(const vector<int>& arr, int& idx){
if(arr.empty()) return nullptr;
if(idx >= arr.size() || arr[idx] == 0){
idx++;
return nullptr;
}
TreeNode* node = new TreeNode(arr[idx++]);
node->left = buildTree(arr, idx);
node->right = buildTree(arr, idx);
return node;
}
TreeNode* LCA = nullptr;
TreeNode* check(TreeNode* root, int val1, int val2){
if(root == nullptr) return nullptr;
if(root->val == val1 || root->val == val2) return root;
TreeNode* lc = check(root->left, val1, val2);
TreeNode* rc = check(root->right, val1, val2);
if(lc && rc) return root;
return (lc ? lc : rc);
}
int main(){
//前序增强输入
int n;
cin >> n;
vector<int> arr(n);
for(int i = 0; i < n; i++){
cin >> arr[i];
}
int pa, pb;
cin >> pa >> pb;
int p = 0;
TreeNode* root = buildTree(arr, p);
LCA = check(root, pa, pb);
cout << LCA->val << endl;
return 0;
}