您的位置:首页 > 其它

【二叉树】求二叉树中两个节点的最近公共父节点

2013-10-30 15:03 218 查看
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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: