Problem 619
Maximum Sum BST in Binary Tree
Hard · 30 pts · Tree, Binary Search Tree, Dynamic Programming
Problem
Among all subtrees of a binary tree (a node with all its descendants) that are valid binary search trees, find the largest sum of values. A valid BST has every left-subtree value strictly smaller than the node and every right-subtree value strictly greater, recursively. The empty tree counts as a BST with sum 0, so the answer is never negative. A post-order search returns, for each subtree, whether it is a BST together with its minimum, maximum and sum.
Input
The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.
Output
Print the maximum sum of a BST subtree.
Constraints
1 <= number of nodes <= 40000; -40000 <= value <= 40000
Example input
15 1 4 3 2 4 2 5 null null null null null null 4 6
Example output
20
Explanation
In the tree 1 4 3 2 4 2 5 null null null null null null 4 6, the subtree rooted at 3 (with 2, 5, 4 and 6) is a valid BST with sum 3 + 2 + 5 + 4 + 6 = 20, the largest of any BST subtree.