Maximum Sum BST in Binary Tree
LeetCode 1373 · কঠিন · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Post-order returning (sum, min, max) or 'not a BST'.
আমি Maximum Sum BST in Binary Tree (LeetCode 1373) এভাবে সমাধান করেছি — Tree প্যাটার্নের একটি কঠিন প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
Post-order: each subtree reports whether it's a BST, along with its sum, minimum and maximum. A node forms a BST if both children do and the left max < node < right min; then its sum is a candidate. Any invalid child makes every ancestor invalid too.
Approach
- 1
None → empty (valid, no bounds).
- 2
If either child is invalid, return invalid.
- 3
Check left.max < val < right.min.
- 4
Valid → sum, update the best, return new bounds.
আমি কীভাবে সমাধান করেছি
Post-order BST infoPythonO(n) time · O(h) space
class Solution:
def maxSumBST(self, root):
self.mx = 0
def dfs(root):
if root is None:
return None
ldata = dfs(root.left)
rdata = dfs(root.right)
if ldata is False or rdata is False:
return False
isBST = (ldata["max"] < root.val if ldata else True) and (rdata["min"] > root.val if rdata else True)
if isBST:
total = (ldata["sum"] if ldata else 0) + (rdata["sum"] if rdata else 0) + root.val
self.mx = max(total, self.mx)
return {"sum": total, "min": ldata["min"] if ldata else root.val, "max": rdata["max"] if rdata else root.val}
return False
dfs(root)
return self.mxMaximum Sum BST in Binary Tree — সাধারণ প্রশ্ন
Maximum Sum BST in Binary Tree-এর পেছনে intuition কী?
Post-order: each subtree reports whether it's a BST, along with its sum, minimum and maximum. A node forms a BST if both children do and the left max < node < right min; then its sum is a candidate. Any invalid child makes every ancestor invalid too.
Maximum Sum BST in Binary Tree (LeetCode 1373) কীভাবে সমাধান করবেন?
1. None → empty (valid, no bounds). 2. If either child is invalid, return invalid. 3. Check left.max < val < right.min. 4. Valid → sum, update the best, return new bounds.
Maximum Sum BST in Binary Tree-এর time আর space complexity কত?
Time: O(n)। Space: O(h)। (Accepted approach: Post-order BST info।)
Maximum Sum BST in Binary Tree-এ সাধারণ ভুলগুলো কী?
The best sum starts at 0 — an all-negative tree returns 0 (empty BST).