-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc-257.java
More file actions
38 lines (31 loc) · 922 Bytes
/
lc-257.java
File metadata and controls
38 lines (31 loc) · 922 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
37
38
/**
* 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> res = new ArrayList();
public List<String> binaryTreePaths(TreeNode root) {
if(root!=null)updatePath(root, Integer.toString(root.val));
return res;
}
private void updatePath(TreeNode root, String path) {
if(root.left == null && root.right == null) {
res.add(path);
return;
}
if(root.left != null) {
updatePath(root.left, path + "->" + Integer.toString(root.left.val));
}
if(root.right != null) {
updatePath(root.right, path + "->" + Integer.toString(root.right.val));
}
}
}