257. Binary Tree Paths

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 }

 

 1 public class Solution {
 2     /**
 3      * @param root the root of the binary tree
 4      * @return all root-to-leaf paths
 5      */
 6     public List<String> binaryTreePaths(TreeNode root) {
 7         ArrayList<String> allList = new ArrayList<String>();
 8         helper(root, allList, "");
 9         
10         return allList;
11     }
12 
13     public void helper(TreeNode root, ArrayList<String> allList, String sb) {
14 
15         if (root == null) return;
16         if (sb.length() != 0) {
17             sb += "->";
18         }
19         sb += root.val;
20         if (root.left == null && root.right == null) {
21             allList.add(sb.toString());
22         }
23         helper(root.left, allList, sb);
24         helper(root.right, allList, sb);
25     }
26 }

 

 
posted @ 2016-07-12 07:21  北叶青藤  阅读(166)  评论(0编辑  收藏  举报