oneby7

Binary Search Trees Using the ordering

399. Maximum Sum BST in Binary Tree

Hard

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

1234650253040

Input: root = [50, 4, 30, 2, 6, 25, 40, 1, 3]

Output: 95

Explanation: 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

-9-5-126

Input: root = [2, -5, 6, -9, -1]

Output: 6

Explanation: 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

−10⁹-7-2

Input: root = [-7, -1000000000, -2]

Output: 0

Explanation: 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.

root = [6, 4, 6, 1, 5, null, 9]

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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.