Space
Open
From Fieldwork
Scales
Archive
It's all about carrying state (the current path) through a recursion tree and recognizing the terminal condition.
For this question, top-down (passing the string path down) is quite intuitive.
class Solution:
def binaryTreePaths(self, root):
def dfs(node, path_list):
if not node:
return
# 1. Add current value to the list
path_list.append(str(node.val))
# 2. Check for leaf
if not node.left and not node.right:
res.append("->".join(path_list))
else:
# 3. Recurse down
dfs(node.left, path_list)
dfs(node.right, path_list)
# 4. BACKTRACK: Remove the node so it doesn't leak into the next path
path_list.pop()
res = []
dfs(root, [])
return resPractice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode