257.Binary Tree Paths

Solution1�� accepted

������java
class Solution {
public List binaryTreePaths(TreeNode root) {
List result = new ArrayList<>();
List path = new ArrayList<>();
traverse(result, path, root);
return result;
}

private void traverse(List<String> result, List<Integer> path, TreeNode root) {
    if (root == null) {
        return;
    } 
    path.add(root.val);
    if (root.left == null && root.right == null) {
        result.add(formatList(path));
    } else {
        traverse(result, path, root.left);
        traverse(result, path, root.right);
    }
    path.remove(path.size() - 1);
}

private String formatList(List<Integer> path) {
    StringBuilder sb = new StringBuilder();
    sb.append(path.get(0));
    for (int i = 1; i < path.size(); i++) {
        sb.append("->" + path.get(i));
    }
    return sb.toString();
}

}
������

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
traverse(result, "", root);
return result;
}
private void traverse(List<String> result, String path, TreeNode root) {
if (root == null) {
return;
}
path += root.val;
if (root.left == null && root.right == null) {
result.add(path);
} else {
traverse(result, path + "->", root.left);
traverse(result, path + "->", root.right);
}
}
}