Skip to content

Latest commit

 

History

History
33 lines (29 loc) · 1.02 KB

1373.md

File metadata and controls

33 lines (29 loc) · 1.02 KB

1373. Maximum Sum BST in Binary Tree

Solution 1 (time O(n), space O(1))

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def maxSumBST(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.ans = 0

        def dfs(node):
            if node is None:
                return 1, float("inf"), -float("inf"), 0
            left_bst, left_min, left_max, left_sum = dfs(node.left)
            right_bst, right_min, right_max, right_sum = dfs(node.right)
            if left_bst and right_bst and left_max < node.val < right_min:
                t = left_sum + right_sum + node.val
                self.ans = max(self.ans, t)
                return 1, min(left_min, node.val), max(right_max, node.val), t
            return 0, 0, 0, 0

        dfs(root)
        return self.ans