leetcode 257 binary tree paths

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

1
2
3
4
5
   1
/
2 3

5

All root-to-leaf paths are:

1
["1->2->5", "1->3"]

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 {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<String>();
binaryTreePathsFinder(root, "", result);
return result;
}
public void binaryTreePathsFinder(TreeNode root, String path, List<String> result){
if (root == null) return ;
if(root.left == null && root.right == null){
result.add(path + root.val);
}
else if( root.left != null && root.right != null){
path = path + root.val + "->";
binaryTreePathsFinder(root.left, path, result);
binaryTreePathsFinder(root.right, path, result);
}
else if(root.left != null && root.right == null){
path = path + root.val + "->";
binaryTreePathsFinder(root.left, path, result);
}
else{
path = path + root.val + "->";
binaryTreePathsFinder(root.right, path, result);
}
}
}

1
2
3
4
5
6
7
8
9
10
public List<String> binaryTreePaths(TreeNode root) {
List<String> answer = new ArrayList<String>();
if (root != null) searchBT(root, "", answer);
return answer;
}
private void searchBT(TreeNode root, String path, List<String> answer) {
if (root.left == null && root.right == null) answer.add(path + root.val);
if (root.left != null) searchBT(root.left, path + root.val + "->", answer);
if (root.right != null) searchBT(root.right, path + root.val + "->", answer);
}