-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinary_257.java
More file actions
41 lines (38 loc) · 1.44 KB
/
Binary_257.java
File metadata and controls
41 lines (38 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Binary_257 {
// Refer to the following link for two iterative solutions: dfs+stack and bfs+queue
// https://leetcode.com/problems/binary-tree-paths/discuss/68272/Python-solutions-(dfs%2Bstack-bfs%2Bqueue-dfs-recursively).
public List<String> binaryTreePaths(TreeNode root) {
// My first solution using recursion
/*
if (root == null)
return Arrays.asList();
if (root.left == null && root.right == null)
return Arrays.asList(String.valueOf(root.val));
ArrayList<String> res = new ArrayList<>();
if (root.left != null) {
for (String s : binaryTreePaths(root.left))
res.add(root.val + "->" + s);
}
if (root.right != null) {
for (String s : binaryTreePaths(root.right))
res.add(root.val + "->" + s);
}
return res;
*/
List<String> res = new ArrayList<>();
if (root != null)
searchBT(root, "", res);
return res;
}
private void searchBT(TreeNode root, String path, List<String> res) {
if (root.left == null && root.right == null)
res.add(path+root.val);
if (root.left != null)
searchBT(root.left, path+root.val+"->", res);
if (root.right != null)
searchBT(root.right, path+root.val+"->", res);
}
}