二叉树的最近公共祖先问题
问题描述:
给你一棵二叉树,给你两个节点值,要你求出他们的最近公共祖先节点问题。
解题思路:
问题会有两种情况,其中一个节点是另一个节点的祖先节点次数只需要返回该节点就行或祖先节点的左子树找到了一个值右子树找到另外一个值时返回当前节点就行。
参考链接
#include "bits/stdc++.h"
using namespace std;
struct node{
int val;
node* left;
node* right;
};
node* build(node* root, vector<int> z, vector<int> h) {
if(z.size() == 0) return NULL;
root = new node;
root->val = h.back();
vector<int> z_l, z_r, h_l, h_r;
for(int i = 0; i < z.size(); i++) {
if(z[i] == h.back()) break;
z_l.push_back(z[i]);
}
for(int i = z_l.size() + 1; i < z.size(); i++) {
z_r.push_back(z[i]);
}
h.resize(h.size() - 1);
for(int i = 0; i < z_l.size(); i++) {
h_l.push_back(h[i]);
}
for(int i = z_l.size(); i < h.size(); i++) {
h_r.push_back(h[i]);
}
root->left = build(root->left, z_l, h_l);
root->right = build(root->right, z_r, h_r);
return root;
}
void traver(node* root ) {
if(root == NULL) return;
cout<<root->val<<" ";
traver(root->left);
traver(root->right);
}
node* ancestor(node* root, int x, int y) { // 值为x, y的节点的公共祖先节点
if(root == NULL || root->val == x || root->val == y) return root;
node* left = ancestor(root->left, x, y);
node* right = ancestor(root->right, x, y);
if(left != NULL && right != NULL) return root;
if(left != NULL) return left;
if(right != NULL) return right;
return NULL;
}
int main() {
int n;
cin>>n;
vector<int> z(n), h(n);
for(int i = 0; i < n; i++) { // 中序
cin>>z[i];
}
for(int i = 0; i < n; i++) { // 后序
cin>>h[i];
}
node* root = NULL;
root = build(root, z, h);
cout<<ancestor(root, 4, 3)->val<<endl;
// traver(root);
return 0;
}