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 ArrayList<>();
String s="";
if(root==null) return res;
preOrder(root, res, s);
return res;
}
public void preOrder(TreeNode root, List<String> res, String s){
s=s+root.val+"->";
//only when both children are null, means end of path, one child is null, means a turn node, so keep going down
if(root.left==null && root.right==null){
res.add(s.substring(0,s.length()-2));
return;
}
if(root.left!=null)
preOrder(root.left, res, s);
if(root.right!=null)
preOrder(root.right, res, s);
}
}