LeetCode "Largest BST Subtree"

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode "Largest BST Subtree"相关的知识,希望对你有一定的参考价值。

A typical recursion use:

class Solution(object):
    max_size = 0

    # return: isValid, minVal, maxVal, nodeCnt
    def go(self, root):
        if root.left is None and root.right is None:
            #print (root.val, True, root.val, root.val, 1)
            self.max_size = max(self.max_size, 1)
            return True, root.val, root.val, 1
        leftOk = rightOk = True
        leftMin = leftMax = rightMin = rightMax = root.val
        leftCnt = rightCnt = 0
        if root.left:
            leftValid, leftMin, leftMax, leftCnt = self.go(root.left)
            leftOk = leftValid and leftMax < root.val
        if root.right:
            rightValid, rightMin, rightMax, rightCnt = self.go(root.right)
            rightOk = rightValid and rightMin > root.val

        if leftOk and rightOk:
            self.max_size = max(self.max_size, leftCnt + rightCnt + 1)
        #print (root.val, leftOk and rightOk, leftMin, rightMax, leftCnt + rightCnt + 1)
        return leftOk and rightOk, leftMin, rightMax, leftCnt + rightCnt + 1

    def largestBSTSubtree(self, root):
        if root is None: return self.max_size
        self.go(root)
        return self.max_size

 

以上是关于LeetCode "Largest BST Subtree"的主要内容,如果未能解决你的问题,请参考以下文章

[Lintcode]184. Largest Number/[Leetcode]179. Largest Number

#Leetcode# 179. Largest Number

LeetCode Largest Divisible Subset

Leetcode410. Split Array Largest Sum

leetcode 179 Largest Number

LeetCode(179) Largest Number