@@ -4,8 +4,8 @@ def __init__(self, val=0, left=None, right=None):
4
4
self .left = left
5
5
self .right = right
6
6
7
- def maxSumBST (root : TreeNode ) -> int :
8
7
8
+ def maxSumBST (root : TreeNode ) -> int :
9
9
"""
10
10
The solution traverses a binary tree to find the maximum sum of
11
11
keys in any subtree that is a Binary Search Tree (BST). It uses
@@ -39,30 +39,25 @@ def maxSumBST(root: TreeNode) -> int:
39
39
40
40
def solver (node ):
41
41
nonlocal ans
42
-
42
+
43
43
if not node :
44
- return True , float (' inf' ), float (' -inf' ), 0 # Valid BST, min, max, sum
45
-
44
+ return True , float (" inf" ), float (" -inf" ), 0 # Valid BST, min, max, sum
45
+
46
46
isLeftValid , min_left , max_left , sum_left = solver (node .left )
47
47
isRightValid , min_right , max_right , sum_right = solver (node .right )
48
48
49
49
if isLeftValid and isRightValid and max_left < node .val < min_right :
50
50
total_sum = sum_left + sum_right + node .val
51
51
ans = max (ans , total_sum )
52
52
return True , min (min_left , node .val ), max (max_right , node .val ), total_sum
53
-
53
+
54
54
return False , - 1 , - 1 , - 1 # Not a valid BST
55
55
56
56
solver (root )
57
57
return ans
58
-
59
- if __name__ == "__main__" :
60
-
61
- import doctest
62
- doctest .testmod ()
63
-
64
-
65
-
66
58
67
59
60
+ if __name__ == "__main__" :
61
+ import doctest
68
62
63
+ doctest .testmod ()
0 commit comments