Lowest Common Ancestor(LCA)

1.是二叉搜索树

struct TreeNode  
{  
    int val;  
    TreeNode *left, *right;  
};   
  
TreeNode *LCA(TreeNode *root, TreeNode *p1, TreeNode *p2)  
{  
    while(1) {   
        if (root->val > p1->val && root->val > p2->val) root = root->left;   
        else if (root->val < p1->val && root->val < p2->val) root = root->right;  
        else return root;  
    }      
}      

2.不是二叉搜索树,是二叉树
2.1有父指针
分别从两个结点出发,得到两个到根结点的单向链表,转换为求两个单向链表的第一个公共结点。

2.2没有父指针
(1)http://zhedahht.blog.163.com/blog/static/25411174201081263815813/

(2)

TreeNode *LCA(TreeNode *root,TreeNode *p1,TreeNode *p2)  
{  
    if(!root||root==p1||root==p2)return root;  
    TreeNode *left=LCA(root->left,p1,p2);  
    TreeNode *right=LCA(root->right,p1,p2);
    if(left&&right)return root;  
    else if(left)return left;  
    else if(right)return right;  
    else return NULL;  
}  

(3)Tarjan算法

(4)转换为RMQ问题
http://blog.csdn.net/hz5034/article/details/44084087

3.不是二叉树,是树

struct TreeNode
{
	int val;
	vector<TreeNode *>children;
};

bool dfs(TreeNode *root,TreeNode *&p,vector<TreeNode *> &path)
{
	if(!root)return false;
	path.push_back(root);
	if(root==p)return true;
	for(vector<TreeNode *>::iterator i=root->children.begin();i!=root->children.end();++i)
	{
		if(dfs(*i,p,path))return true;
	}
	path.pop_back();
	return false;
}

TreeNode *LCA(TreeNode *root,TreeNode *p1,TreeNode *p2)
{
	if(!root||!p1||!p2)return NULL;
	vector<TreeNode *> path1,path2;
	dfs(root,p1,path1);
	dfs(root,p2,path2);
	TreeNode *res;
	for(int i=0;i<path1.size()&&i<path2.size();++i)
	{
		if(path1[i]==path2[i])res=path1[i];
		else break;
	}
	return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值