0
点赞
收藏
分享

微信扫一扫

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

狗啃月亮_Rachel 2022-03-30 阅读 24
c++leetcode

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;
}
举报

相关推荐

0 条评论