<p>Given a <strong>binary tree</strong> <code>root</code>, return <em>the maximum sum of all keys of <strong>any</strong> sub-tree which is also a Binary Search Tree (BST)</em>.</p>

<p>Assume a BST is defined as follows:</p>

<ul>
	<li>The left subtree of a node contains only nodes with keys <strong>less than</strong> the node&#39;s key.</li>
	<li>The right subtree of a node contains only nodes with keys <strong>greater than</strong> the node&#39;s key.</li>
	<li>Both the left and right subtrees must also be binary search trees.</li>
</ul>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<p><img alt="" src="https://assets.leetcode.com/uploads/2020/01/30/sample_1_1709.png" style="width: 320px; height: 250px;" /></p>

<pre>
<strong>Input:</strong> root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]
<strong>Output:</strong> 20
<strong>Explanation:</strong> Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.
</pre>

<p><strong class="example">Example 2:</strong></p>

<p><img alt="" src="https://assets.leetcode.com/uploads/2020/01/30/sample_2_1709.png" style="width: 134px; height: 180px;" /></p>

<pre>
<strong>Input:</strong> root = [4,3,null,1,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong> Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> root = [-4,-2,-5]
<strong>Output:</strong> 0
<strong>Explanation:</strong> All values are negatives. Return an empty BST.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 4 * 10<sup>4</sup>]</code>.</li>
	<li><code>-4 * 10<sup>4</sup> &lt;= Node.val &lt;= 4 * 10<sup>4</sup></code></li>
</ul>

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
from collections import deque
class Solution:
    """
    `Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).`

    Let's forget about part of problem `the maximum sum of all keys`. We will first try to solve
    `which is also a Binary Search Tree (BST).`

    Idea1: Brute force way.
        > for each node, we check if its a BST. If it is, then all the nodes below it will also
            be BST.
        > for the node which is BST, we find sum of all the childs.
        time: O(n*n*n) = O(n**3)
            -> traverse whole tree
            -> check if node BST
            -> sum all below
        space: O(n)
        > Time Limit Exceeded
    
    Idea2: 
        same as maxSumBSTBruteForce, but we calculate the sum of nodes while determining
        whether the tree is BST
        time: O(n**2)
            -> traverse whole tree
            -> check if node BST and sum all below
        space: O(n)

    Idea3:
        Can we merge the traversing and check if node BST and sum all below?
    """
    def maxSumBST(self, root: Optional[TreeNode]) -> int:
        max_bst_sum = 0
        def isBST(node):
            nonlocal max_bst_sum
            if not node:
                return (True, None, None, 0)

            is_bst_left, left_max, left_min, leftsum  = True, node.val, node.val, 0
            if node.left:
                is_bst_left, left_max, left_min, leftsum = isBST(node.left)

            is_bst_right, right_max, right_min, rightsum = True, node.val, node.val, 0
            if node.right:
                is_bst_right, right_max, right_min, rightsum = isBST(node.right)

            if (
                not is_bst_left 
                or (node.left and left_max >= node.val) 
                or not is_bst_right
                or (node.right and right_min <= node.val)
            ):
                return (False, None, None, None)

            curr_sum = node.val+leftsum+rightsum
            max_bst_sum = max(max_bst_sum, curr_sum)
            return (True, right_max, left_min, curr_sum)
        
        isBST(root)
        return max_bst_sum


    def maxSumBSTIdea2(self, root: Optional[TreeNode]) -> int:

        """
        greatest of left should be smaller than current
        lowest of right should be greater than current 
        """
        def isBST(node):
            if not node:
                return (True, None, None, 0)

            is_bst_left, left_max, left_min, leftsum  = True, node.val, node.val, 0
            if node.left:
                is_bst_left, left_max, left_min, leftsum = isBST(node.left)
            if not is_bst_left: # return early even if one side is not BST
                return (False, None, None, None)

            is_bst_right, right_max, right_min, rightsum = True, node.val, node.val, 0
            if node.right:
                is_bst_right, right_max, right_min, rightsum = isBST(node.right)
            if not is_bst_right: # return early even if one side is not BST
                return (False, None, None, None)

            if (node.left and left_max >= node.val) or (node.right and right_min <= node.val):
                return (False, None, None, None)

            return (True, right_max, left_min, node.val+leftsum+rightsum)

        max_bst_sum = 0
        qu = deque()
        qu.append(root)
        while qu:
            node = qu.popleft()
            is_bst, _, _, allsum  = isBST(node)
            if is_bst:
                max_bst_sum = max(max_bst_sum, allsum)

            if node.left:
                qu.append(node.left)
            if node.right:
                qu.append(node.right)

        return max_bst_sum

    


    def maxSumBSTIdea1(self, root: Optional[TreeNode]) -> int:

        """
        greatest of left should be smaller than current
        lowest of right should be greater than current 
        """
        def isBST(node):
            if not node:
                return (True, None, None)

            is_bst_left, left_max, left_min = True, node.val, node.val
            if node.left:
                is_bst_left, left_max, left_min = isBST(node.left)
            if not is_bst_left: # return early even if one side is not BST
                return (False, None, None)

            is_bst_right, right_max, right_min = True, node.val, node.val
            if node.right:
                is_bst_right, right_max, right_min = isBST(node.right)
            if not is_bst_right: # return early even if one side is not BST
                return (False, None, None)

            if (node.left and left_max >= node.val) or (node.right and right_min <= node.val):
                return (False, None, None)

            return (True, right_max, left_min)

        def sum_below(node):
            if not node:
                return 0
            return node.val + sum_below(node.left) + sum_below(node.right)

        max_bst_sum = 0
        qu = deque()
        qu.append((root, None))
        while qu:
            node, is_bst = qu.popleft()
            if not is_bst:
                is_bst, _, _ = isBST(node)
            if is_bst:
                max_bst_sum = max(max_bst_sum, sum_below(node))

            if node.left:
                qu.append((node.left, is_bst))
            if node.right:
                qu.append((node.right, is_bst))

        return max_bst_sum

197