-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary Tree Paths.java
53 lines (49 loc) · 1.12 KB
/
Binary Tree Paths.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
/*
Given a binary tree, return all root-to-leaf paths.
1
/ \
2 3
\
5
All root-to-leaf paths are:
[
"1->2->5",
"1->3"
]
time = O(n)
space = O(n^2) build new string every level
*/
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
// write your code here
List<String> result = new ArrayList<>();
if (root == null) {
return result;
}
helper(root, "", result);
return result;
}
private void helper(TreeNode root, String path, List<String> result) {
if (root.left == null && root.right == null) {
result.add(path + root.val);
return;
}
if (root.left != null) {
helper(root.left, path + root.val + "->", result);
}
if (root.right != null) {
helper(root.right, path + root.val + "->", result);
}
}
}