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.