Skip to content

Commit ac1bdae

Browse files
authored
Create maximum-sum-bst-in-binary-tree.py
1 parent 2b5435f commit ac1bdae

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Time: O(n)
2+
# Space: O(h)
3+
4+
# Definition for a binary tree node.
5+
class TreeNode(object):
6+
def __init__(self, x):
7+
self.val = x
8+
self.left = None
9+
self.right = None
10+
11+
12+
class Solution(object):
13+
def maxSumBST(self, root):
14+
"""
15+
:type root: TreeNode
16+
:rtype: int
17+
"""
18+
def dfs(node, result):
19+
if not node:
20+
return True, 0, float("inf"), float("-inf")
21+
lvalid, lsum, lmin, lmax = dfs(node.left, result)
22+
rvalid, rsum, rmin, rmax = dfs(node.right, result)
23+
if lvalid and rvalid and lmax < node.val < rmin:
24+
total = lsum + node.val + rsum
25+
result[0] = max(result[0], total)
26+
return True, total, min(lmin, node.val), max(node.val, rmax)
27+
return False, 0, 0, 0
28+
29+
result = [0]
30+
dfs(root, result)
31+
return result[0]

0 commit comments

Comments
 (0)