-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathBinaryTreePaths257.java
71 lines (63 loc) · 1.78 KB
/
BinaryTreePaths257.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Given a binary tree, return all root-to-leaf paths.
*
* For example, given the following binary tree:
*
* 1
* / \
* 2 3
* \
* 5
* All root-to-leaf paths are:
*
* ["1->2->5", "1->3"]
*
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinaryTreePaths257 {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
binaryTreePaths(root, new StringBuilder(), res);
return res;
}
public void binaryTreePaths(TreeNode root, StringBuilder path, List<String> res) {
if (root == null) return;
path.append(root.val);
if (root.left == null && root.right == null) {
res.add(path.toString());
return;
}
path.append("->");
int l = path.length();
binaryTreePaths(root.left, path, res);
path.delete(l, path.length());
binaryTreePaths(root.right, path, res);
path.delete(l, path.length());
}
/**
* https://leetcode.com/problems/binary-tree-paths/discuss/68278/My-Java-solution-in-DFS-BFS-recursion
*/
public List<String> binaryTreePaths2(TreeNode root) {
List<String> sList=new LinkedList<String>();
if (root==null) return sList;
if (root.left==null && root.right==null) {
sList.add(Integer.toString(root.val));
return sList;
}
for (String s: binaryTreePaths(root.left)) {
sList.add(Integer.toString(root.val)+"->"+s);
}
for (String s: binaryTreePaths(root.right)) {
sList.add(Integer.toString(root.val)+"->"+s);
}
return sList;
}
}