BTNode *pResult = null;
//权值方法
int GetFirstCommonFather(BTNode *root,BTNode *p1,BTNode *p2)
{
if(pResult != null) return 0; //如果result所指向的不为null,说明已经找到。
if(root == null) return 0;
int sum = 0;
if(root == p1 || root == p2) sum += 1;
sum += GetFirstCommonFather(root->lchild,p1,p2);
sum += GetFirstCommonFather(root->rchild,p1,p2);
if(sum == 2 && pResult == null)
{
pResult = root;
return 0;
}
return sum;
}
//更牛逼的方法
BTNode *GetFirstCommonFather(BTNode *root,BTNode *p1,BTNode *p2)
{
if(root == NULL)
return NULL;
if(root == p1 || root == p2)
{
return root;
}
BTNode *pLeft = GetFirstCommonFather(root->lchild,p1,p2);
BTNode *pRight = GetFirstCommonFather(root->rchild,p1,p2);
if(pLeft && pRight)
{
return root;
}
return pLeft ? pLeft : pRight;
}
http://sxnuwhui.blog.163.com/blog/static/13706837320129225952111/
【二叉树】求二叉树中两个节点的最近公共父节点
最新推荐文章于 2019-09-16 16:49:02 发布