bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 1373. Maximum Sum BST in Binary Tree

1373. Maximum Sum BST in Binary Tree

Leetcode Solutions

Postorder Traversal and BST Validation

  1. Define a helper function that returns a tuple containing the sum of the subtree, the maximum and minimum values within the subtree, and a boolean indicating whether it's a valid BST.
  2. Perform a postorder traversal (left, right, root).
  3. At each node, get the results from the left and right subtrees.
  4. Check if the current node's value is greater than the maximum value of the left subtree and less than the minimum value of the right subtree.
  5. If the current subtree is a valid BST, calculate its sum and update the maximum sum found so far.
  6. Return the sum, maximum, minimum, and validity of the current subtree.
  7. If the current subtree is not a valid BST, return the sum as 0 and mark it as invalid.
  8. After the traversal, return the maximum sum found.
UML Thumbnail

In-Order Traversal with Global State

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...
bugfree Icon
OR