-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
76 lines (71 loc) · 1.89 KB
/
Solution.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<>();
if (root == null) {
return paths;
}
findPaths(root, new StringBuilder(), paths);
return paths;
}
private void findPaths(TreeNode node, StringBuilder path, List<String> paths) {
int len = path.length(); // Save the current length of the path
path.append(node.val); // Append the current node value
if (node.left == null && node.right == null) {
// Leaf node, add path to the list
paths.add(path.toString());
} else {
// Non-leaf node, continue the path
path.append("->");
if (node.left != null) {
findPaths(node.left, path, paths);
}
if (node.right != null) {
findPaths(node.right, path, paths);
}
}
// Backtrack to the previous state
path.setLength(len);
}
}
/*
* /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*
* class Solution {
* public List<String> binaryTreePaths(TreeNode root) {
* List<String> paths = new ArrayList<>();
* if (root == null) {
* return paths;
* }
* findPaths(root, "", paths);
* return paths;
* }
*
* private void findPaths(TreeNode node, String path, List<String> paths) {
* if (node.left == null && node.right == null) {
*
* paths.add(path + node.val);
* } else {
*
* if (node.left != null) {
* findPaths(node.left, path + node.val + "->", paths);
* }
* if (node.right != null) {
* findPaths(node.right, path + node.val + "->", paths);
* }
* }
* }}
*
*/