NewCodeTemplate
This commit is contained in:
51
模板/树/LCA最近共同祖先.cpp
Normal file
51
模板/树/LCA最近共同祖先.cpp
Normal file
@@ -0,0 +1,51 @@
|
||||
#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;
|
||||
}
|
||||
Reference in New Issue
Block a user