leetcode236.二叉树的最低公共祖先(未完成,为看懂)

1.递归
参考:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/65369/Short-and-clean-C%2B%2B-solution

递归没看懂,如果递归函数是返回最低祖先的话,那么当l不为空的话,说明p,q在左子树中,那么r一定是为空的,但是代码里if(l && r) return root;说不通

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {//从root中查找p,q的最低公共祖先并返回祖先节点指针
    if (!root || !p || !q) { //root,p,q中有一个为nullptr,返回nullptr
        return NULL;
    }    
    if (root == p || root == q) {//root==p代表从p中查p,q的最低祖先,此时最低祖先应该为p(即p是q的祖先)
        return root;
    }    
    //如果p,q不存在一个是另一个的祖先关系
    TreeNode* l = lowestCommonAncestor(root->left, p, q); //从左子树去查并返回祖先指针
    TreeNode* r = lowestCommonAncestor(root->right, p, q); //从右子树去查并返回祖先指针   
    if (l && r) { //l,r都不为空,说明p,q分布在当前节点的左右子树当中,则当前节点为最低公共祖先
        return root;
    }    
    return l!=nullptr? l : r;//如果l不为空,r为空,说明p,q都在左子树当中,且l为
}

猜你喜欢

转载自blog.csdn.net/aikudexue/article/details/89817479
今日推荐