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