Given the root of a binary tree, find the largest subtree, which is also a Binary Search Tree (BST), where the largest means subtree has the largest number of nodes.
A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties:
The left subtree values are less than the value of their parent (root) node's value.
The right subtree values are greater than the value of their parent (root) node's value.
Note: A subtree must include all of its descendants.
Example 1:
Input: root = [10,5,15,1,8,null,7]
Output: 3
Explanation: The Largest BST Subtree in this case is the highlighted one. The return value is the subtree's size, which is 3.
The number of nodes in the tree is in the range [0, 104].
-104 <= Node.val <= 104
Follow up: Can you figure out ways to solve it with O(n) time complexity?
Solutions
Solution 1
Thinking
Find the size of the largest BST subtree. Validating a BST at every node repeats work. A subtree is a BST iff both sides are BSTs and the root sits between their extrema.
Postorder returns \((\min,\max,size)\). If left-max \(<\) root \(<\) right-min, merge sizes and update the answer; otherwise return sentinels \((-\infty,\infty,0)\) so ancestors cannot absorb it. An empty tree returns \((\infty,-\infty,0)\) so a leaf succeeds.
1 2 3 4 5 6 7 8 910111213141516171819202122
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:deflargestBSTSubtree(self,root:Optional[TreeNode])->int:defdfs(root):ifrootisNone:returninf,-inf,0lmi,lmx,ln=dfs(root.left)rmi,rmx,rn=dfs(root.right)nonlocalansiflmx<root.val<rmi:ans=max(ans,ln+rn+1)returnmin(lmi,root.val),max(rmx,root.val),ln+rn+1return-inf,inf,0ans=0dfs(root)returnans
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funclargestBSTSubtree(root*TreeNode)int{ans:=0vardfsfunc(root*TreeNode)[]intdfs=func(root*TreeNode)[]int{ifroot==nil{return[]int{math.MaxInt32,math.MinInt32,0}}left:=dfs(root.Left)right:=dfs(root.Right)ifleft[1]<root.Val&&root.Val<right[0]{ans=max(ans,left[2]+right[2]+1)return[]int{min(root.Val,left[0]),max(root.Val,right[1]),left[2]+right[2]+1}}return[]int{math.MinInt32,math.MaxInt32,0}}dfs(root)returnans}