leetcode 236 二叉树的最近公共祖先

二叉树的最近公共祖先

使用dfs求解,根据返回值判断是否存在节点。返回值如果是空,表明当前子树不存在p或q。把p和q分为两种情况,一种是在p或q在当前节点,或者p或q分别在当前节点的左右子树上。

如果当前节点是p或者q,返回当前节点。

struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
    if(root==NULL||root==p||root==q){
        return root;
    }
    struct TreeNode* left_res=lowestCommonAncestor(root->left,p,q);
    struct TreeNode* right_res=lowestCommonAncestor(root->right,p,q);
    if(left_res==NULL){
        return right_res;
    }
    if(right_res==NULL){
        return left_res;
    }
    return root;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值