二叉樹-最近公共祖先(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);
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章