码迷,mamicode.com
首页 > 其他好文 > 详细

*Binary Tree Paths

时间:2015-08-31 06:27:15      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

*Binary Tree Paths

标签:

原文地址:http://www.cnblogs.com/hygeia/p/4772107.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!