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

Binary Tree Paths

时间:2016-07-12 07:54:32      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

Given a binary tree, return all root-to-leaf paths.

Example

Given the following binary tree:

   1
 /   2     3
   5

All root-to-leaf paths are:

[
  "1->2->5",
  "1->3"
]

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param root the root of the binary tree
15      * @return all root-to-leaf paths
16      */
17     public List<String> binaryTreePaths(TreeNode root) {
18         ArrayList<ArrayList<Integer>> allList = new ArrayList<ArrayList<Integer>>();
19         ArrayList<Integer> list = new ArrayList<Integer>();
20         helper(root, allList, list);
21 
22         List<String> strList = new ArrayList<String>();
23 
24         for (int i = 0; i < allList.size(); i++) {
25             List<Integer> tempList = allList.get(i);
26             StringBuilder sb = new StringBuilder();
27             for (int j = 0; j < tempList.size(); j++) {
28                 sb.append(tempList.get(j));
29                 if (j != tempList.size() - 1) {
30                     sb.append("->");
31                 }
32             }
33             strList.add(sb.toString());
34         }
35         return strList;
36     }
37 
38     public void helper(TreeNode root, ArrayList<ArrayList<Integer>> allList, ArrayList<Integer> list) {
39 
40         if (root == null)
41             return;
42 
43         list.add(root.val);
44         if (root.left == null && root.right == null) {
45             allList.add(new ArrayList<Integer>(list));
46         }
47         helper(root.left, allList, list);
48 
49         helper(root.right, allList, list);
50         list.remove(list.size() - 1);
51     }
52 }

 

 

Binary Tree Paths

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5662239.html

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