Binary Tree Paths

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 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<String> binaryTreePaths(TreeNode root) {
12         List<String> result = new ArrayList<>();
13         if (root == null) {
14             return result;
15         }
16         helper(root, result, String.valueOf(root.val));
17         return result;
18     }
19     private void helper(TreeNode root, List<String> result, String path) {
20         if (root == null) {
21             return;
22         }
23         if (root.left == null && root.right == null) {
24             result.add(path);
25             return;
26         }
27         if (root.left != null) {
28             helper(root.left, result, path + "->" + String.valueOf(root.left.val));
29         }
30         if (root.right != null) {
31             helper(root.right, result, path + "->" + String.valueOf(root.right.val));
32         }
33     }
34 }

 

posted @ 2016-03-17 09:02  YuriFLAG  阅读(143)  评论(0)    收藏  举报