forked from szl0072/Leetcode-Solution-Code
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinaryTreePaths.java
55 lines (50 loc) · 1.2 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
43
44
45
46
47
48
49
50
51
52
53
54
55
package leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Edward on 25/07/2017.
*/
public class BinaryTreePaths {
/**
* 257. Binary Tree Paths
* Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
3
/ \
9 20
/ \
15 7
["3->9->15", "3->9->7", "3->20]
case :
3
/ \
9 20
/ \
15 7
3->9->15
3->9->7
3->20
["3->9->15", "3->9->7", "3->20]
time : O(n);
space : O(n);
* @param root
* @return
*/
public static List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root == null) return res;
helper(res, root, "");
return res;
}
public static void helper(List<String> res, TreeNode root, String path) {
if (root.left == null && root.right == null) {
res.add(path + root.val);
}
if (root.left != null) {
helper(res, root.left, path + root.val + "->");
}
if (root.right != null) {
helper(res, root.right, path + root.val + "->");
}
}
}