Leetcode 333. Largest BST Subtree
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.
Here's an example:
10 / \ 5 15 / \ \ 1 8 7
The Largest BST Subtree in this case is the highlighted one.
The return value is the subtree's size, which is 3.
思路: 根据Hint,可以递归调用98题 Validate Binary Search Tree.
1. 写一个子函数,递归的计算tree的大小。
2. 从root开始,检查是否为BST,如果是,输出treeSize(root)。如果不是return max(largestBSTSubtree(root.right), largestBSTSubtree(root.left))
1 class Solution(object): 2 def largestBSTSubtree(self, root): 3 """ 4 :type root: TreeNode 5 :rtype: int 6 """ 7 if self.isValidBST(root): 8 return self.treeSize(root) 9 else: 10 return max(self.largestBSTSubtree(root.left), self.largestBSTSubtree(root.right)) 11 12 13 def isValidBST(self, root): 14 """ 15 :type root: TreeNode 16 :rtype: bool 17 """ 18 maxInt = 2147483647 19 minInt = -2147483648 20 21 return self.isBSTHelper(root, minInt, maxInt) 22 23 def isBSTHelper(self, root, minVal, maxVal): 24 if not root: 25 return True 26 27 if root.val <= maxVal and root.val >= minVal and self.isBSTHelper(root.left, minVal, root.val - 1) and self.isBSTHelper(root.right, root.val + 1, maxVal): 28 return True 29 else: 30 return False 31 32 def treeSize(self, root): 33 if not root: 34 return 0 35 else: 36 return 1 + self.treeSize(root.left) + self.treeSize(root.right) 37