Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 1373 · Tree

Maximum Sum BST in Binary Tree

LeetCode 1373 · கடினம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Post-order returning (sum, min, max) or 'not a BST'.

கடினம்Dynamic ProgrammingTreeDepth-First SearchBinary Search TreeBinary Tree
LeetCode இல் திற ↗

நான் 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. 1

    None → empty (valid, no bounds).

  2. 2

    If either child is invalid, return invalid.

  3. 3

    Check left.max < val < right.min.

  4. 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.mx
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

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