二叉树最近公共祖先递归算法
我目前搜到的网上的版本都是这样的;
BTree NearestAncestor(BTree T,BTree p,BTree q){
if(T==NULL||T==p||T==q) return T;
BTree left = NearestAncestor(T->lchild,p,q);
BTree right = NearestAncestor(T->rchild,p,q);
if(left==NULL) return right;
if(right==NULL) return left;
return T;
}
个人感觉这个递归函数将两个功能杂糅在了一起,一方面返回了最近祖先,另一方面又在寻找p、q节点的位置,功能不是很明确,不好理解。
因此我将其拆解成两个函数
函数1 Search() 用于寻找p,q节点是否在该子树上
函数2 NearestAncestor()用于找到p、q的最近公共祖先
bool Search(BTree T,BTree p,BTree q){ //以T为根的树上有没有p节点或者q节点
if(T==NULL) return 0;
if(T==p||T==q) return 1;
return (Search(T->lchild,p,q)||Search(T->rchild,p,q));
}
BTree NearestAncestor(BTree T,BTree p,BTree q){ //p节点和q节点的最近公共祖先
if(T==NULL) return NULL; //空树,返回空指针
if(T==p||T==q) return T; //根节点为p或q,那么p和q的最近祖先一定是根节点
bool left = Search(T->lchild,p,q); //左子树上有没有p或q;
bool right = Search(T->rchild,p,q); //右子树上有没有p或q;
if(!right) return NearestAncestor(T->lchild,p,q); //如果右子树上没有,那么p和q一定都在左子树上,
//递归寻找左子树;
if(!left) return NearestAncestor(T->rchild,p,q);
return T; //如果左子树上有p或q,右子树上也有p或q,那么
//p和q的最近公共祖先是根节点;
}