257. Binary Tree Paths
Problem
Return every root-to-leaf path of a binary tree as a string of values joined by "->", in any order.
Example: [1,2,3,null,5] → ["1->2->5","1->3"]
DFS with the path so far; at a leaf, join it with ->.
Complexity: O(n · h).
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
res = []
def dfs(node, path):
if not node:
return
path = path + [str(node.val)]
if not node.left and not node.right:
res.append("->".join(path))
dfs(node.left, path)
dfs(node.right, path)
dfs(root, [])
return res
assert sorted(Solution().binaryTreePaths(make_tree([1, 2, 3, None, 5]))) == sorted(["1->2->5", "1->3"])
assert Solution().binaryTreePaths(make_tree([1])) == ["1"]
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
dfs(root, "", res);
return res;
}
private void dfs(TreeNode n, String path, List<String> res) {
if (n == null) return;
path = path.isEmpty() ? String.valueOf(n.val) : path + "->" + n.val;
if (n.left == null && n.right == null) res.add(path);
dfs(n.left, path, res);
dfs(n.right, path, res);
}
}
func binaryTreePaths(root *TreeNode) []string {
res := []string{}
var dfs func(node *TreeNode, path string)
dfs = func(node *TreeNode, path string) {
if node == nil {
return
}
path += strconv.Itoa(node.Val)
if node.Left == nil && node.Right == nil {
res = append(res, path)
return
}
dfs(node.Left, path+"->")
dfs(node.Right, path+"->")
}
dfs(root, "")
return res
}