Description
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"]
Code
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if(root == null)
return res;
findPaths(root, res, "");
return res;
}
void findPaths(TreeNode root, List<String> res, String sb){
if(root.left == null && root.right == null){
res.add(sb + root.val);
}
if(root.left != null){
findPaths(root.left, res, sb + root.val + "->");
}
if(root.right != null){
findPaths(root.right, res, sb + root.val + "->");
}
}
}