AlgoMaster Logo

Binary Tree Paths

tree=[1, 2, 3, 4, 5]
1class Solution {
2    public List<String> binaryTreePaths(TreeNode root) {
3        List<String> paths = new ArrayList<>();
4        if (root != null) {
5            dfs(root, "", paths);
6        }
7        return paths;
8    }
9
10    private void dfs(TreeNode node, String path, List<String> paths) {
11        // Append current node to the path
12        path += node.val;
13        // If it's a leaf, append the path to paths list
14        if (node.left == null && node.right == null) {
15            paths.add(path);
16        } else {
17            // If not a leaf, continue exploring further with arrows
18            if (node.left != null) 
19              dfs(node.left, path + "->", paths);
20            if (node.right != null) 
21              dfs(node.right, path + "->", paths);
22        }
23    }
24}
0 / 18
12345