The number of nodes in the tree is in the range [1, 100].
-100 <= Node.val <= 100
Solutions
Solution 1: DFS
We can use depth-first search to traverse the entire binary tree. Each time, we add the current node to the path. If the current node is a leaf node, we add the entire path to the answer. Otherwise, we continue to recursively traverse the child nodes of the node. Finally, when the recursion ends and returns to the current node, we need to remove the current node from the path.
The time complexity is \(O(n^2)\), and the space complexity is \(O(n)\). Where \(n\) is the number of nodes in the binary tree.
1 2 3 4 5 6 7 8 91011121314151617181920212223
# 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 = rightclassSolution:defbinaryTreePaths(self,root:Optional[TreeNode])->List[str]:defdfs(root:Optional[TreeNode]):ifrootisNone:returnt.append(str(root.val))ifroot.leftisNoneandroot.rightisNone:ans.append("->".join(t))else:dfs(root.left)dfs(root.right)t.pop()ans=[]t=[]dfs(root)returnans
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcbinaryTreePaths(root*TreeNode)(ans[]string){t:=[]string{}vardfsfunc(*TreeNode)dfs=func(root*TreeNode){ifroot==nil{return}t=append(t,strconv.Itoa(root.Val))ifroot.Left==nil&&root.Right==nil{ans=append(ans,strings.Join(t,"->"))}else{dfs(root.Left)dfs(root.Right)}t=t[:len(t)-1]}dfs(root)return}