题目:
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 public List<String> binaryTreePaths(TreeNode root) 2 { 3 List<String> res = new ArrayList<String>(); 4 StringBuilder sb = new StringBuilder(); 5 if(root==null)return res; 6 helper(root,res,sb); 7 return res; 8 9 } 10 11 public void helper(TreeNode root, List<String> res, StringBuilder sb) 12 { 13 if(root.left==null&&root.right==null) 14 { 15 sb.append(root.val); 16 res.add(sb.toString()); 17 return ; 18 } 19 20 sb.append(root.val); 21 sb.append("->"); 22 23 if(root.left!=null) 24 { 25 helper(root.left,res, new StringBuilder(sb)); 26 27 } 28 29 if(root.right!=null) 30 { 31 helper(root.right,res, new StringBuilder(sb)); 32 } 33 34 }
红字部分如果只是用 “sb” 就会出现以下错误的结果:
Submission Result: Wrong AnswerMore Details
Input:[1,2,3]
Output:["1->2","1->23"]
Expected:["1->2","1->3"]
StringBuilder:
http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
reference: https://leetcode.com/discuss/52250/binary-tree-paths-dfs-java-solution