二叉树-最近公共祖先(LCA)

思路:递归的思想,如果当前节点的左子树和右子树各包括一个节点,则该节点就为最近公共祖先;如果当前节点等于其中的一个节点,则当前节点为最近公共祖先;如果当前节点的左子树或者右子树包括两个节点,则需要递归求该节点的左子树或者有子树。


struct Node{
	int data;
	Node* left, *right;
};
//count the number of p and q
//这个函数这样写的很巧妙,如果将root==p||root==q
//写在前面的话,我们将分不清另一个节点所在的子树就会比较麻烦 
int getNumpq(Node *root,Node *p,Node *q){
	if(!root) return 0;
	int res=getNumpq(root->left,p,q)+getNumpq(root->right,p,q);
	if(root==p||root==q)
	    return 1+res;
	else
	    return res;
}
//Lowest Common Ancestor
Node* LCA(Node *root,Node *p,Node *q){
	if(!root||!p||!q) return NULL;
	if(root==p||root==q) return root;
	int matches=getNumpq(root->left,p,q);
	if(matches==1)
	    return root;
	else if(matches==2)
	    return LCA(root->left,p,q);
	else
	    return LCA(root->right,p,q);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值