给定一个二叉树,找到其中最大的二叉搜索树(BST)子树,其中最大指的是子树节点数最多的。
注意:
子树必须包含其所有后代。
示例:
输入: [10,5,15,1,8,null,7]
10
/ \
5 15
/ \ \
1 8 7
输出: 3
解释: 高亮部分为最大的 BST 子树。
返回值 3 在这个样例中为子树大小。
进阶:
你能想出用 O(n) 的时间复杂度解决这个问题吗
class Solution:
def largestBSTSubtree(self, root: TreeNode) -> int:
def process(head):
# 消息体:BST大小(节点数)、BST头部、BST最小值、BST最大值
# 左右子树都需要的消息体结构
if not head:
return 0, None, float('inf'), float('-inf')
lsize, lhead, lmin, lmax = process(head.left)
rsize, rhead, rmin, rmax = process(head.right)
# 当前层操作
includeItSelf = 0
# 并没有用上lmin和rmax但是得返回,因为消息体是这么整合的
if lhead == head.left and rhead == head.right and lmax < head.val < rmin:
includeItSelf = lsize + 1 + rsize
# 当前层要返回给上层的东西,处理成消息体结构
maxSize = max(lsize, rsize, includeItSelf)
# 也不知道这一层是上一层的左还是右,又验证了消息体的整合
maxHead = lhead if lsize > rsize else rhead
# 如果算上当前节点了,更新一下maxHead
if maxSize == includeItSelf:
maxHead = head
return maxSize, maxHead, min(lmin, rmin, head.val), max(lmax, rmax, head.val)
return process(root)[0]