imashutosh51

Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST

Jul 25th, 2022 (edited)
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. '''
  2. We are given a binary tree, and we need to find the maximum sum of any subtree that is also a BST.
  3.  
  4. For each node, we need to know whether its subtree is a BST, the sum of that subtree, and the minimum and maximum values in that subtree.
  5.  
  6. A subtree rooted at a node is a BST if its left and right subtrees are BSTs, the maximum value in the left subtree is less than the node’s value, and the minimum value in the right subtree is greater than the node’s value.
  7.  
  8. By keeping track of the sum of valid BST subtrees while traversing, we can update the global maximum sum whenever we encounter a valid BST.
  9.  
  10. If a subtree is not a BST, it cannot contribute to the sum of any larger BST, so we mark it invalid and propagate that up.
  11.  
  12. Using a post-order traversal (DFS), we compute these values for left and right subtrees first, then determine the validity, sum, min, and max for the current node.
  13.  
  14. This approach allows us to solve the problem in a single pass with O(N) time and O(H) space, where N is the number of nodes and H is the tree height.
  15. '''
  16.  
  17. from math import inf
  18.  
  19. # DFS function outside the class
  20. def dfs(node, ans):
  21.     if not node:
  22.         return True, 0, inf, -inf
  23.    
  24.     l_bst, l_sum, l_min, l_max = dfs(node.left, ans)
  25.     r_bst, r_sum, r_min, r_max = dfs(node.right, ans)
  26.    
  27.     if l_bst and r_bst and l_max < node.val < r_min:
  28.         cur_sum = l_sum + r_sum + node.val
  29.         ans[0] = max(ans[0], cur_sum)  # update max sum
  30.         return True, cur_sum, min(l_min, node.val), max(r_max, node.val)
  31.    
  32.     return False, 0, 0, 0
  33.  
  34. class Solution:
  35.     def maxSumBST(self, root):
  36.         ans = [0]  # use list to pass by reference
  37.         dfs(root, ans)
  38.         return ans[0]
  39.  
Advertisement
Add Comment
Please, Sign In to add comment