首页 > 其他 > 详细

257. Binary Tree Paths

时间:2016-08-11 08:35:38      阅读:229      评论:0      收藏:0      [点我收藏+]

还是有bug,因为需要注意处理根节点,如果每往下走一点就增加"->x"的话,返回的结果会是“->a->b->c”

试着开始就左右分开走,但是因为如果左右节点都为空的根节点又需要单独处理很麻烦,所以每次就是添加到List<Stirng>res里面的时候把头上的"->"切掉

 1     public List<String> binaryTreePaths(TreeNode root) {
 2         List<String> res = new ArrayList<String>();
 3         if(root == null) {
 4             return res;
 5         }
 6         traversal(res, "", root);
 7         return res;
 8     }
 9     
10     private void traversal(List<String> res, String cur, TreeNode root) {
11         if(root == null) {
12             return;
13         }
14         cur += "->";
15         cur += String.valueOf(root.val);
16         if(root.left == null && root.right == null) {
17             cur = cur.substring(2);
18             res.add(cur);
19             return;
20         }
21         traversal(res, cur, root.left);
22         traversal(res, cur, root.right);
23     }

 

257. Binary Tree Paths

原文:http://www.cnblogs.com/warmland/p/5759546.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!