forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Tree Paths.java
More file actions
35 lines (34 loc) · 808 Bytes
/
Binary Tree Paths.java
File metadata and controls
35 lines (34 loc) · 808 Bytes
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<String> list;
public List<String> binaryTreePaths(TreeNode root) {
list = new ArrayList<>();
if (root == null) {
return list;
}
helper(root, new StringBuilder());
return list;
}
private void helper(TreeNode root, StringBuilder sb) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
sb.append(root.val);
list.add(sb.toString());
}
else {
sb.append(root.val).append("->");
helper(root.left, new StringBuilder(sb.toString()));
helper(root.right, new StringBuilder(sb.toString()));
}
}
}