/**
* 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> paths = new ArrayList<>();
if (root == null) {
return paths;
}
if (root.left == null && root.right == null) {
paths.add("" + root.val);
return paths;
}
List<String> leftPath = binaryTreePaths(root.left);
List<String> rightPath = binaryTreePaths(root.right);
for (String path : leftPath) {
paths.add(root.val + "->" + path);
}
for (String path : rightPath) {
paths.add(root.val + "->" + path);
}
return paths;
}
}
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<>();
binaryTreePaths(root, "", paths);
return paths;
}
private void binaryTreePaths(TreeNode root, String path, List<String> paths) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
paths.add(path + root.val);
}
binaryTreePaths(root.left, path + root.val + "->", paths);
binaryTreePaths(root.right, path + root.val + "->", paths);
}
}