Public class Num257 binary tree all paths {List<String> ans = new ArrayList<>(); public List<String> binaryTreePaths(TreeNode root) { dfs(root, new StringBuilder());return ans;
    }

    private void dfs(TreeNode root, StringBuilder path) {
        if (root == null) {
            return; } //root is not empty, you need to add the path of this nodeif(path.length() ! = 0) { path.append("- >"); } path.append(root.val); // Return the answer if it is a leafif (root.left == null && root.right == null) {
            ans.add(path.toString());
            return; } int len = path.length(); dfs(root.left, path); // Unselect path.delete(len, path.length()); dfs(root.right, path); }}Copy the code