-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
59 lines (48 loc) · 1.53 KB
/
Solution.java
File metadata and controls
59 lines (48 loc) · 1.53 KB
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<String>();
if (root == null)
return result;
Stack<TreeNode> path = new Stack<TreeNode>();
path.push(root);
binaryTreePaths(root, result, path);
path.pop();
return result;
}
private void binaryTreePaths(TreeNode root, List<String> result, Stack<TreeNode> path) {
if (root.left == null && root.right == null) {
String pathString = path2String(path);
result.add(pathString);
return;
}
if (root.left != null) {
path.push(root.left);
binaryTreePaths(root.left, result, path);
path.pop();
}
if (root.right != null) {
path.push(root.right);
binaryTreePaths(root.right, result, path);
path.pop();
}
}
private String path2String(Stack<TreeNode> path) {
StringBuilder sb = new StringBuilder();
Iterator<TreeNode> iter = path.iterator();
while (iter.hasNext()) {
sb.append(iter.next().val);
if (iter.hasNext())
sb.append("->");
}
return sb.toString();
}
}