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; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<String>();
if(root == null) {
return result;
}
String str = "";
dfs(root, result, str);
return result;
}
private void dfs(TreeNode root, List<String> result, String str) {
if(str.length() == 0) {
str = str + Integer.toString(root.val);
} else {
str = str + "->" + Integer.toString(root.val);
}
if (root.left != null) {
dfs(root.left, result, str);
}
if (root.right != null) {
dfs(root.right, result, str);
}
if (root.left == null && root.right == null) {
result.add(new String(str));
}
}
}