Skip to content

Commit c9ab283

Browse files
committed
add solution of problem 257: binary tree path
1 parent 13fc5bb commit c9ab283

2 files changed

Lines changed: 75 additions & 0 deletions

File tree

‎BinaryTreePaths257/README.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
Given a binary tree, return all root-to-leaf paths.
2+
3+
For example, given the following binary tree:
4+
5+
```
6+
1
7+
/ \
8+
2 3
9+
\
10+
5
11+
```
12+
All root-to-leaf paths are:
13+
14+
```
15+
["1->2->5", "1->3"]
16+
```

‎BinaryTreePaths257/Solution.java‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
public class Solution {
11+
public List<String> binaryTreePaths(TreeNode root) {
12+
List<String> result = new ArrayList<String>();
13+
14+
if (root == null)
15+
return result;
16+
17+
Stack<TreeNode> path = new Stack<TreeNode>();
18+
19+
path.push(root);
20+
binaryTreePaths(root, result, path);
21+
path.pop();
22+
23+
return result;
24+
}
25+
26+
private void binaryTreePaths(TreeNode root, List<String> result, Stack<TreeNode> path) {
27+
if (root.left == null && root.right == null) {
28+
String pathString = path2String(path);
29+
result.add(pathString);
30+
return;
31+
}
32+
33+
if (root.left != null) {
34+
path.push(root.left);
35+
binaryTreePaths(root.left, result, path);
36+
path.pop();
37+
}
38+
39+
if (root.right != null) {
40+
path.push(root.right);
41+
binaryTreePaths(root.right, result, path);
42+
path.pop();
43+
}
44+
}
45+
46+
private String path2String(Stack<TreeNode> path) {
47+
StringBuilder sb = new StringBuilder();
48+
Iterator<TreeNode> iter = path.iterator();
49+
50+
while (iter.hasNext()) {
51+
sb.append(iter.next().val);
52+
53+
if (iter.hasNext())
54+
sb.append("->");
55+
}
56+
57+
return sb.toString();
58+
}
59+
}

0 commit comments

Comments
 (0)