# My Java solution with StringBuilder may help u

• ``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void help(List<String> list, TreeNode node, StringBuilder sb) {
if (node == null)
return;
int len=sb.length();
sb.append(node.val);
if (node.left == null && node.right == null) {
sb.setLength(len);
return;
}
sb.append("->");
help(list, node.left, sb);
help(list, node.right, sb);
sb.setLength(len);
}

public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<String>();
help(res, root, new StringBuilder());
return res;
}
}``````

• I do not quite understand why you have to set the new length to the StringBuilder sb. Could you please explain more?

Thanks!

• If u can see the difference of the following solutions, u will understand.

``````public class Solution {
public void help(List<String> list, TreeNode node, String s) {
if (node == null)
return;
int len = s.length();
s += node.val;
if (node.left == null && node.right == null) {

s = s.substring(0, len);
return;
}
s += "->";
help(list, node.left, s);
help(list, node.right, s);
s = s.substring(0, len);
}

public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<String>();
help(res, root, "");
return res;
}
}

public class Solution {
public void help(List<String> list, TreeNode node, String s) {
if (node == null)
return;
if (node.left == null && node.right == null) {
return;
}
help(list, node.left, s + node.val + "->");
help(list, node.right, s + node.val + "->");
}

public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<String>();
help(res, root, "");
return res;
}
}``````

• Thanks, these two solutions are easy to understand.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.