-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTreePaths257.java
More file actions
36 lines (34 loc) · 962 Bytes
/
Copy pathbinaryTreePaths257.java
File metadata and controls
36 lines (34 loc) · 962 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
32
33
34
35
36
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private List<String> ret = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if (root == null) return ret;
String path = root.val + "";
if (root.left == null && root.right == null) {
ret.add(path);
return ret;
}
btPathRecur(root.left, path);
btPathRecur(root.right, path);
return ret;
}
// f(nodeLeaf): add to ret
private void btPathRecur(TreeNode root, String path) {
if (root == null) return;
String p = path + "->" + root.val;
if (root.left == null && root.right == null) {
this.ret.add(p);
return;
}
btPathRecur(root.left, p);
btPathRecur(root.right, p);
}
}