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"]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new LinkedList<String>();
if (root == null) {
return res;
}
binaryTreePathsHelper(res, root, new StringBuilder(""));
return res;
}
private void binaryTreePathsHelper(List<String> res, TreeNode node, StringBuilder sb) {
if (node.left == null && node.right == null) {
StringBuilder temp = new StringBuilder(sb);
temp.append(node.val);
res.add(temp.toString());
}
if (node.left != null) {
StringBuilder temp = new StringBuilder(sb);
temp.append(node.val).append("->");
binaryTreePathsHelper(res, node.left, temp);
}
if (node.right != null) {
StringBuilder temp = new StringBuilder(sb);
temp.append(node.val).append("->");
binaryTreePathsHelper(res, node.right, temp);
}
}
}