Limited time: AI code review, hints, mock interviews, whiteboard analysis, and all Pro features are unlocked. Enroll

Maximum Sum BST in Binary Tree

Hard

Topics
TreeDFSBinary Search TreeDynamic Programming

Given the root of a binary tree, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST). A valid BST requires every node in the left subtree to be strictly less than the node, and every node in the right subtree to be strictly greater. If no sub-tree is a BST with positive sum, return 0.

Example 1

Input:  root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]
Output: 20

Example 2

Input:  root = [4,3,null,1,2]
Output: 2

Example 3

Input:  root = [-4,-2,-5]
Output: 0

Constraints

  • 1 <= number of nodes <= 4*10^4
  • -4*10^4 <= Node.val <= 4*10^4.
Run ⌘' · Submit ⌘⏎
SensAI SensAI
Beta
Listening...
Tap mic to stop voice mode

Unlock AI Features

One click to activate - no payment, no credit card. Just sign in and you're in.

AI code review and hints
SensAI chat assistant
AI mock interviews
Whiteboard analysis
100% free during early access