LeetCode solutions by tgic

Binary Tree Paths

https://leetcode.com/problems/binary-tree-paths

Last Update 2015-08-16 15:34:16 +0000 View on Github

Source code Read on Github

 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 
12     List<String> merge(int v, List<String> subPath){
13         return subPath.stream()
14                 .map(p -> v + "->" + p)
15                 .collect(Collectors.toList());
16     }
17 
18     public List<String> binaryTreePaths(TreeNode root) {
19         List<String> path = new ArrayList<>();
20 
21         if(root == null) return path;
22 
23         if(root.left == null && root.right == null) {
24             // leaf
25             return Arrays.asList("" + root.val);
26         }
27 
28         if(root.left != null){
29             path.addAll(merge(root.val, binaryTreePaths(root.left)));
30         }
31 
32         if(root.right != null) {
33             path.addAll(merge(root.val, binaryTreePaths(root.right)));
34         }
35 
36         return path;
37     }
38 }
comments powered by Disqus

LeetCode solutions by tgic

  • LeetCode solutions by tgic
  • [email protected]
  • Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
  • tg123
  • tg123/leetcode

LeetCode java solutions by tgic