?LeetCode刷題實(shí)戰(zhàn)333:最大 BST 子樹(shù)
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 子樹(shù)。
返回值 3 在這個(gè)樣例中為子樹(shù)大小。
解題
思路一:判斷每個(gè)節(jié)點(diǎn)是否是二叉搜索樹(shù)
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)
LeetCode1-320題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)321:拼接最大數(shù)
LeetCode刷題實(shí)戰(zhàn)322:零錢(qián)兌換
LeetCode刷題實(shí)戰(zhàn)323:無(wú)向圖中連通分量的數(shù)目
LeetCode刷題實(shí)戰(zhàn)324:擺動(dòng)排序 II
LeetCode刷題實(shí)戰(zhàn)325:和等于 k 的最長(zhǎng)子數(shù)組長(zhǎng)度
