MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / solver

Function solver

data_structures/binary_tree/maximum_sum_bst.py:49–69  ·  view source on GitHub ↗

Returns the maximum sum by making recursive calls >>> t1 = TreeNode(1) >>> print(solver(t1)) 1

(node: TreeNode | None)

Source from the content-addressed store, hash-verified

47 ans: int = 0
48
49 def solver(node: TreeNode | None) -> tuple[bool, int, int, int]:
50 """
51 Returns the maximum sum by making recursive calls
52 >>> t1 = TreeNode(1)
53 >>> print(solver(t1))
54 1
55 """
56 nonlocal ans
57
58 if not node:
59 return True, INT_MAX, INT_MIN, 0 # Valid BST, min, max, sum
60
61 is_left_valid, min_left, max_left, sum_left = solver(node.left)
62 is_right_valid, min_right, max_right, sum_right = solver(node.right)
63
64 if is_left_valid and is_right_valid and max_left < node.val < min_right:
65 total_sum = sum_left + sum_right + node.val
66 ans = max(ans, total_sum)
67 return True, min(min_left, node.val), max(max_right, node.val), total_sum
68
69 return False, -1, -1, -1 # Not a valid BST
70
71 solver(root)
72 return ans

Callers 1

max_sum_bstFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected