Maximum Sum BST in a Binary Tree
Problem statement
Given the root of a binary tree, find the maximum sum of node values among all subtrees that are valid binary search trees.
A valid BST has every left-subtree value strictly smaller than its root and every right-subtree value strictly larger. Return 0 when every valid non-empty BST subtree has a negative sum.
Function
maxSumBST(root: TreeNode) → intExamples
Example 1
root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]return = 20The subtree rooted at 3 is a BST with sum 20.
Example 2
root = [4,3,null,1,2]return = 2The leaf with value 2 is the best valid BST subtree.
Example 3
root = [-4,-2,-5]return = 0All valid BST sums are negative, so zero is returned.
Constraints
- The tree contains between
0and5000nodes. -10000 ≤ Node.val ≤ 10000.