Binary Search Trees Using the ordering
399. Maximum Sum BST in Binary Tree
You are given root, the root node of a binary tree. Look at every subtree that is a binary search tree, and
return the largest sum of the values in one of them.
A subtree is a node together with all of the nodes below it: its children, their children, and so on down to the leaves. It cannot leave any of them out. A subtree is a binary search tree (BST) when, at every node in it, every value in the node's left subtree is smaller than the node's value, and every value in its right subtree is larger. Values in the tree can repeat, but a subtree that holds two equal values is not a BST. The empty subtree counts as a BST with a sum of 0, so the answer is never negative.
The examples write a tree level by level, from left to right, with null where a child is missing. So
root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The
missing children after the last node are left out.
Example 1
Input: root = [50, 4, 30, 2, 6, 25, 40, 1, 3]
95Explanation: The subtree under 30 holds 30, 25 and 40. It is a BST, and its sum is 95. The subtree under 4 is a BST with more nodes, but its sum is only 16. The whole tree is not a BST, because 30 is on the right of 50 but smaller than it.
Example 2
Input: root = [2, -5, 6, -9, -1]
6Explanation: The whole tree is a BST, but its sum is -7. The negative values pull every larger subtree down, so the best one is the single node 6.
Example 3
Input: root = [-7, -1000000000, -2]
0Explanation: Every value is negative, so every subtree with a node in it has a negative sum. The empty subtree, with a sum of 0, is the best.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109- The tree has at most 1000 levels.
Clarifying questions
What you would ask an interviewer before writing any code.