Sum Root to Leaf Numbers
LeetCode 129 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Carry the path's digits; add at leaves.
मैंने 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
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.
मैंने कैसे हल किया
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.totalSum 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.