leetcode - 236. 二叉树的最近公共祖先
题目

代码
#include <iostream>
#include <map>
using namespace std;
typedef struct TreeNode{
int val;
struct TreeNode *left, *right;
}TreeNode, *BiTree;
map<int, TreeNode*> father;
map<int, bool> visited;
void dfs(TreeNode *root){
if(root->left){
father[root->left->val] = root;
dfs(root->left);
}
if(root->right){
father[root->right->val] = root;
dfs(root->right);
}
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root){
return NULL;
}
father[root->val] = NULL;
dfs(root);
while(p){
visited[p->val] = true;
p = father[p->val];
}
while(q){
if(visited[q->val]){
return q;
}
q = father[q->val];
}
return NULL;
}
int main(){
TreeNode *root, *p, *q, *res;
res = lowestCommonAncestor(root, p, q);
return 0;
}