Leetcode Problem 1373. Maximum Sum BST in Binary Tree
1373. Maximum Sum BST in Binary Tree
Leetcode Solutions
Postorder Traversal and BST Validation
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.
Perform a postorder traversal (left, right, root).
At each node, get the results from the left and right subtrees.
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.
If the current subtree is a valid BST, calculate its sum and update the maximum sum found so far.
Return the sum, maximum, minimum, and validity of the current subtree.
If the current subtree is not a valid BST, return the sum as 0 and mark it as invalid.
After the traversal, return the maximum sum found.