Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 129 · Root-to-Leaf Paths

Sum Root to Leaf Numbers

LeetCode 129 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Carry the path's digits; add at leaves.

మధ్యస్థంTreeDepth-First SearchBinary Tree
LeetCode లో తెరవండి ↗

నేను Sum Root to Leaf Numbers (LeetCode 129) ను ఇలా పరిష్కరించాను — Root-to-Leaf Paths ప్యాటర్న్‌లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

Each root-to-leaf path spells a number. Build the digits as you go down (here as a string), and when you hit a leaf, add that number to the total.

Approach

  1. 1

    dfs(node, path): append node.val to the path.

  2. 2

    At a leaf, add int(path) to the sum.

  3. 3

    Otherwise recurse into both children.

నేను ఎలా పరిష్కరించాను

DFS building digitsPythonO(n·h) time
class Solution:
    def sumNumbers(self, root):
        self.total = 0

        def dfs(node, path):
            if node is not None:
                path += str(node.val)
                if node.left is None and node.right is None:
                    self.total += int(path)
                    return
                dfs(node.left, path)
                dfs(node.right, path)
        dfs(root, "")
        return self.total
స్టెప్-త్రూ లోడ్ అవుతోంది…

Sum Root to Leaf Numbers — తరచూ అడిగే ప్రశ్నలు

Sum Root to Leaf Numbers వెనుక ఉన్న intuition ఏమిటి?

Each root-to-leaf path spells a number. Build the digits as you go down (here as a string), and when you hit a leaf, add that number to the total.

Sum Root to Leaf Numbers (LeetCode 129) ను ఎలా పరిష్కరించాలి?

1. dfs(node, path): append node.val to the path. 2. At a leaf, add int(path) to the sum. 3. Otherwise recurse into both children.

Sum Root to Leaf Numbers యొక్క time, space complexity ఎంత?

Time: O(n · h) with strings (O(n) with path·10 + val). Space: O(h). (Accepted approach: DFS building digits.)

Sum Root to Leaf Numbers లో సాధారణ పొరపాట్లు ఏమిటి?

path·10 + val avoids string building.