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.