Given the root
of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
TreeNode
, which has three attributes: val
(the value of the node), left
(pointer to the left child), and right
(pointer to the right child).None
), we will append the current path to the result list.None
), we return an empty list.from typing import List, Optional
# 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
def binaryTreePaths(root: Optional[TreeNode]) -> List[str]:
def dfs(node: TreeNode, path: List[int], paths: List[str]):
if node is None:
return
# Add current node to the path
path.append(node.val)
# If it's a leaf node, record the path
if not node.left and not node.right:
paths.append("->".join(map(str, path)))
else:
# Recur on the left and right subtree
dfs(node.left, path, paths)
dfs(node.right, path, paths)
# Backtrack
path.pop()
paths = []
dfs(root, [], paths)
return paths
This approach is efficient given the constraints and provides clear and concise root-to-leaf paths.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?