-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBinaryTreePaths.java
More file actions
31 lines (30 loc) · 869 Bytes
/
BinaryTreePaths.java
File metadata and controls
31 lines (30 loc) · 869 Bytes
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
if (root == null) {
return new ArrayList<String>();
}
List<String> result = new ArrayList<>();
buildPath(root, "", result);
return result;
}
public void buildPath(TreeNode root, String path, List<String> result) {
if (root.left == null && root.right == null) {
result.add(path + root.val);
}
if (root.left != null) {
buildPath(root.left, path + root.val + "->", result);
}
if (root.right != null) {
buildPath(root.right, path + root.val + "->", result);
}
}
}