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

मैंने 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).