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).