|
| 1 | +class TreeNode: |
| 2 | + def __init__(self, val=0, left=None, right=None): |
| 3 | + self.val = val |
| 4 | + self.left = left |
| 5 | + self.right = right |
| 6 | + |
| 7 | +def maxSumBST(root: TreeNode) -> int: |
| 8 | + |
| 9 | + """ |
| 10 | + The solution traverses a binary tree to find the maximum sum of |
| 11 | + keys in any subtree that is a Binary Search Tree (BST). It uses |
| 12 | + recursion to validate BST properties and calculates sums, returning |
| 13 | + the highest sum found among all valid BST subtrees. |
| 14 | +
|
| 15 | + >>> t1 = TreeNode(4) |
| 16 | + >>> t1.left = TreeNode(3) |
| 17 | + >>> t1.left.left = TreeNode(1) |
| 18 | + >>> t1.left.right = TreeNode(2) |
| 19 | + >>> print(maxSumBST(t1)) |
| 20 | + 2 |
| 21 | + >>> t2 = TreeNode(-4) |
| 22 | + >>> t2.left = TreeNode(-2) |
| 23 | + >>> t2.right = TreeNode(-5) |
| 24 | + >>> print(maxSumBST(t2)) |
| 25 | + 0 |
| 26 | + >>> t3 = TreeNode(1) |
| 27 | + >>> t3.left = TreeNode(4) |
| 28 | + >>> t3.left.left = TreeNode(2) |
| 29 | + >>> t3.left.right = TreeNode(4) |
| 30 | + >>> t3.right = TreeNode(3) |
| 31 | + >>> t3.right.left = TreeNode(2) |
| 32 | + >>> t3.right.right = TreeNode(5) |
| 33 | + >>> t3.right.right.left = TreeNode(4) |
| 34 | + >>> t3.right.right.right = TreeNode(6) |
| 35 | + >>> print(maxSumBST(t3)) |
| 36 | + 20 |
| 37 | + """ |
| 38 | + ans = 0 |
| 39 | + |
| 40 | + def solver(node): |
| 41 | + nonlocal ans |
| 42 | + |
| 43 | + if not node: |
| 44 | + return True, float('inf'), float('-inf'), 0 # Valid BST, min, max, sum |
| 45 | + |
| 46 | + isLeftValid, min_left, max_left, sum_left = solver(node.left) |
| 47 | + isRightValid, min_right, max_right, sum_right = solver(node.right) |
| 48 | + |
| 49 | + if isLeftValid and isRightValid and max_left < node.val < min_right: |
| 50 | + total_sum = sum_left + sum_right + node.val |
| 51 | + ans = max(ans, total_sum) |
| 52 | + return True, min(min_left, node.val), max(max_right, node.val), total_sum |
| 53 | + |
| 54 | + return False, -1, -1, -1 # Not a valid BST |
| 55 | + |
| 56 | + solver(root) |
| 57 | + return ans |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + |
| 61 | + import doctest |
| 62 | + doctest.testmod() |
| 63 | + |
| 64 | + |
| 65 | + |
| 66 | + |
| 67 | + |
| 68 | + |
0 commit comments