Skip to content

Commit b342c62

Browse files
solves bainary tree paths
1 parent 5ca08dd commit b342c62

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@
7979
| 246 | [Strobogramatic Number](https://leetcode.com/problems/strobogrammatic-number) | Easy |
8080
| 252 | [Meeting Rooms](https://leetcode.com/problems/meeting-rooms) | Easy | |
8181
| 256 | [Paint House](https://leetcode.com/problems/paint-house) | Easy | |
82-
| 257 | [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths) | Easy | |
82+
| 257 | [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)]() |
8383
| 258 | [Add Digits](https://leetcode.com/problems/add-digits) | Easy | |
8484
| 263 | [Ugly Number](https://leetcode.com/problems/ugly-number) | Easy | |
8585
| 266 | [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation) | Easy | |

src/BinaryTreePaths.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
public class BinaryTreePaths {
5+
public static void main(String[] args) {
6+
String[] array = {"hello", "1", "2"};
7+
List<CharSequence> list = new ArrayList<>();
8+
list.add("1");
9+
list.add("2");
10+
list.add("3");
11+
System.out.println(String.join("->", list));
12+
}
13+
14+
private static class TreeNode {
15+
int val;
16+
TreeNode left;
17+
TreeNode right;
18+
}
19+
20+
public static List<String> binaryTreePaths(TreeNode root) {
21+
List<String> result = new ArrayList<>();
22+
binaryTreePaths(root, new ArrayList<CharSequence>(), result);
23+
return result;
24+
}
25+
26+
private static void binaryTreePaths(TreeNode root, List<CharSequence> path, List<String> paths) {
27+
if (root == null) {
28+
return;
29+
}
30+
31+
path.add(root.val + "");
32+
33+
if (isLeafNode(root)) {
34+
paths.add(String.join("->", path));
35+
path.remove(path.size() - 1);
36+
return;
37+
}
38+
39+
binaryTreePaths(root.left, path, paths);
40+
binaryTreePaths(root.right, path, paths);
41+
path.remove(path.size() - 1);
42+
}
43+
44+
private static boolean isLeafNode(TreeNode root) {
45+
return root.left == null && root.right == null;
46+
}
47+
}

0 commit comments

Comments
 (0)