A binary tree, return all root-to-node paths. For example,
1
/ \
2 3
\
5
return : ["1","12","125","13"]
Here is my code: but it gets ["1","12","125","1","13"], the root print twice? how to correct my code?
Thanks.
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
StringBuilder sb = new StringBuilder();
LinkedList<Integer> list = new LinkedList<>();
if (root == null) {
return result;
}
helper(root, result, sb);
return result;
}
public void helper(TreeNode root, List<String> result, StringBuilder sb) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
result.add(sb.append(root.val).toString());
return;
}
int len = sb.length();
if(root.left != null) {
sb.append(root.val);
result.add(sb.toString());
helper(root.left, result, sb);
sb.setLength(len);//remove the last node value, backtracking
}
if(root.right != null) {
sb.append(root.val);
result.add(sb.toString());
helper(root.right, result, sb);
sb.setLength(len);
}
}
}