Poison

257. Binary Tree Paths

DFS
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
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new LinkedList<>();
Deque<Integer> path = new LinkedList<>();

dfs(list, path, root);

return list;
}

private void dfs(List<String> list, Deque<Integer> path, TreeNode node) {
if (node == null) {
return;
}

path.add(node.val);

if (node.left == null && node.right == null) {
list.add(pathToString(path));
}

dfs(list, path, node.left);
dfs(list, path, node.right);
path.removeLast();
}

private String pathToString(Deque<Integer> path) {
return path.stream().map(String::valueOf).collect(Collectors.joining("->"));
}
}
BFS
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
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new LinkedList<>();

Queue<TreeNode> queue = new LinkedList<>();
Queue<String> pathQueue = new LinkedList<>();
queue.add(root);
pathQueue.add(String.valueOf(root.val));

while (!queue.isEmpty()) {
TreeNode node = queue.poll();
String path = pathQueue.poll();

if (node.left == null && node.right == null) {
list.add(path);
}

if (node.left != null) {
queue.add(node.left);
pathQueue.add(path + "->" + node.left.val);
}
if (node.right != null) {
queue.add(node.right);
pathQueue.add(path + "->" + node.right.val);
}
}

return list;
}
}
Reference

257. Binary Tree Paths