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.