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"]
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<String> binaryTreePaths(TreeNode root) { 12 List<String> res = new ArrayList<String>(); 13 if (root == null) return res; 14 helper(root, res, ""); 15 return res; 16 } 17 18 public void helper(TreeNode root, List<String> res, String item) { 19 if (root.left == null && root.right == null) { 20 if (item.length() == 0) { 21 res.add("" + root.val); 22 } 23 else { 24 res.add(item + "->" + root.val); 25 } 26 return; 27 } 28 if (root.left != null) 29 helper(root.left, res, item.length()==0? ""+root.val : item+"->"+root.val); 30 if (root.right != null) 31 helper(root.right, res, item.length()==0? ""+root.val : item+"->"+root.val); 32 33 } 34 }