Largest Sum of a BST Rooted Subtree. Among rooted subtrees of the native binary tree, find the largest sum whose entire subtree is a strict binary search tree.
### Problem
Among rooted subtrees of the native binary tree, find the largest sum whose entire subtree is a strict binary search tree. Every left descendant must be smaller than its ancestor and every right descendant greater. The empty BST with sum 0 is also allowed, as in the original all-negative example. Return the maximum sum.
```cpp
class Solution {
public:
int maxSumBST(TreeNode* root);
};
```
### Examples
**Example 1:**
```text
Input: root = [4,2,6,1,3]
Output: 16
Explanation: The entire tree is a BST and sums to4+2+6+1+3=16.
```
**Example 2:**
```text
Input: root = [-2,-3,-1]
Output: 0
Explanation: Every nonempty candidate has negative sum; the allowed empty BST gives0.
```
### Constraints
- The tree has 1 to 40000 nodes.
- Each key is an integer in `[-40000,40000]`.
- Strict BST ordering is required; the original example explicitly permits the empty BST.
### Contract considerations
Keep the native TreeNode interface and allow the empty candidate when all valid nonempty sums are negative.
```hint Read the boundary condition
A rooted subtree includes all of its descendants. Check strict ordering, duplicate keys, negative values, and the permitted empty candidate.
```
### Boundary reminders
Keep the native TreeNode interface and allow the empty candidate when all valid nonempty sums are negative.
Overview: Largest Sum of a BST Rooted Subtree. Among rooted subtrees of the native binary tree, find the largest sum whose entire subtree is a strict binary search tree.
Among rooted subtrees of the native binary tree, find the largest sum whose entire subtree is a strict binary search tree. Every left descendant must be smaller than its ancestor and every right descendant greater. The empty BST with sum 0 is also allowed, as in the original all-negative example. Return the maximum sum.
class Solution {
public:
int maxSumBST(TreeNode* root);
};
Examples
Example 1:
Input: root = [4,2,6,1,3]
Output: 16
Explanation: The entire tree is a BST and sums to4+2+6+1+3=16.
Example 2:
Input: root = [-2,-3,-1]
Output: 0
Explanation: Every nonempty candidate has negative sum; the allowed empty BST gives0.
Constraints
The tree has 1 to 40000 nodes.
Each key is an integer in
[-40000,40000]
.
Strict BST ordering is required; the original example explicitly permits the empty BST.
Contract considerations
Keep the native TreeNode interface and allow the empty candidate when all valid nonempty sums are negative.
Boundary reminders
Keep the native TreeNode interface and allow the empty candidate when all valid nonempty sums are negative.