Problem
Given the root of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
Algorithm
Use dfs search to save the path.
Code
python3
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
if not root:
return []
if not root.left and not root.right:
return [str(root.val)]
ans = []
save = []
def dfs(node: TreeNode, depth):
if not node.left and not node.right:
s = ""
for i in range(depth):
s += str(save[i]) + "->"
ans.append(s + str(node.val))
return
if len(save) <= depth:
save.append(node.val)
else:
save[depth] = node.val
if node.left:
dfs(node.left, depth+1)
if node.right:
dfs(node.right, depth+1)
dfs(root, 0)
return ans