Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/
2 3
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
tag:
- Tree
java
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<String>();
helper(res, new StringBuilder(), root);
return res;
}
void helper(List<String> res, StringBuilder str, TreeNode root) {
if(root==null) return;
int len = str.length();
str.append(root.val);
if(root.left==null && root.right==null) {
res.add(str.toString());
} else {
str.append("->");
helper(res, str, root.left);
helper(res, str, root.right);
}
str.setLength(len);
}
go