LeetCode刷题实战333:最大 BST 子树
Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it.
Note: A subtree must include all of its descendants.
示例
示例:
输入: [10,5,15,1,8,null,7]
10
/ \
5 15
/ \ \
1 8 7
输出: 3
解释: 高亮部分为最大的 BST 子树。
返回值 3 在这个样例中为子树大小。
解题
思路一:判断每个节点是否是二叉搜索树
class Solution:
def largestBSTSubtree(self, root: TreeNode) -> int:
self.res = 0
def isValid(root, t1, t2):
if not root:
return 0
if root.val >= t2 or root.val <= t1:
return float("-inf")
return 1 + isValid(root.left, t1, root.val) + isValid(root.right, root.val, t2)
def helper(root):
if not root:
return
self.res = max(self.res, isValid(root,float("-inf"), float("inf")) )
helper(root.left)
helper(root.right)
LeetCode刷题实战325:和等于 k 的最长子数组长度