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

मी 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.