235/236. 最低公共祖先

  • 236.分治法,递归调用。先考虑两个退出条件(root为空和root等于p和q的其中一个)。然后用分治法,调用左右子树,最后的判断条件,调用到最后左右子树肯定至少一个有返回值,判断三种条件(左右孩子都有值,左孩子为None,右孩子为None)进行return。
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return None
        if root == p or root == q:
            return root

        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)

        if left and right:
            return root
        if not left:
            return right
        if not right:
            return left
  • 二叉搜索树的公共祖先
    公共祖先的值比左结点大比右结点小。while循环,选择进入左子树还是右子树查找。
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if not root or not p or not q:
            return None
        if p.val > q.val:
            p, q = q, p
        cur = root
        while cur:
            if cur.val >= p.val and cur.val <= q.val:
                return cur
            elif cur.val > p.val:
                cur = cur.left
            else:
                cur = cur.right

猜你喜欢

转载自blog.csdn.net/weixin_34112208/article/details/90926431