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