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

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/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值