-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinaryTreePaths.java
42 lines (34 loc) · 1.01 KB
/
BinaryTreePaths.java
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
42
package com.smlnskgmail.jaman.leetcodejava.easy;
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
import java.util.ArrayList;
import java.util.List;
// https://leetcode.com/problems/binary-tree-paths/
public class BinaryTreePaths {
private final TreeNode input;
public BinaryTreePaths(TreeNode input) {
this.input = input;
}
public List<String> solution() {
List<String> result = new ArrayList<>();
fillPaths(input, "", result);
return result;
}
private void fillPaths(
TreeNode node,
String path,
List<String> paths
) {
if (node == null) {
return;
}
String curr = path.length() > 0
? path + "->" + node.val
: String.valueOf(node.val);
if (node.left == null && node.right == null) {
paths.add(curr);
} else {
fillPaths(node.left, curr, paths);
fillPaths(node.right, curr, paths);
}
}
}