<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
class Solution:
    """
        Determine if a given node n is the root of a BST by checking:
        - if left child is a root of BST, get the max value "a" of left subtree, get sum of left subtree
        - if right child is a root of BST, get the min vlaue "b" of right subtree, get sum of right subtree
        - n is root of BST if a < n.val < b, 
          if yes
            return the (min, max, sum) for the given root
          if no
            return (None, None, max(left_sum, right_num))

        Complexity:
        Time: 
          O(N)
        Space:
          O(depth_of_tree) O(N), Omega(N)


         4 
        / 
       8
      / \
     6   1
    /   / \
    9  -5  4
         \   \
         -3  10  


          4
       -3.    6
    -5  -2.  5. 9

       1    
         10
        -5 20 
    """
    def maxSumBST(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        
        (_, _, _, max_sum, _) = self.find_bst(root)
        if max_sum > 0:
            return max_sum
        else:
            return 0
    
    def find_bst(self, node: Optional[TreeNode]) -> (int, int, int, int, bool):
        if self.is_leaf(node):
            return (node.val, node.val, node.val, node.val, True)            
        
        if node.left:
            (min_left, max_left, sum_left, max_sum_left, left_is_bst) = self.find_bst(node.left)
        if node.right:
            (min_right, max_right, sum_right, max_sum_right, right_is_bst) = self.find_bst(node.right)

        if node.left and node.right:
            if left_is_bst and right_is_bst and (max_left < node.val < min_right):
                ret = (min_left, max_right, sum_left + node.val + sum_right, max(sum_left + node.val + sum_right, max_sum_left, max_sum_right), True)
                print (f"Node {node.val}:  {ret}")
                return ret
            else:
                ret = (None, None, 0, max(max_sum_left, max_sum_right), False)
                print (f"Node {node.val}:  {ret}")
                return ret
        
        elif node.left:
            if left_is_bst and max_left < node.val:
                ret = (min_left, node.val, sum_left + node.val, max(sum_left + node.val, max_sum_left), True)
                print (f"Node {node.val}:  {ret}")
                return ret
            else:
                ret = (None, None, 0, max_sum_left, False)
                print (f"Node {node.val}:  {ret}")
                return ret

        elif node.right:
            if right_is_bst and node.val < min_right:
                ret = (node.val, max_right, node.val + sum_right, max(node.val + sum_right, max_sum_right), True)
                print (f"Node {node.val}:  {ret}")
                return ret
            else:
                ret = (None, None, 0, max_sum_right, False)
                print (f"Node {node.val}:  {ret}")
                return ret

    def is_leaf(self, node: Optional[TreeNode]) -> bool:
        return node and not node.left and not node.right
        
348