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
| class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> list = new LinkedList<>(); Deque<Integer> path = new LinkedList<>();
dfs(list, path, root);
return list; }
private void dfs(List<String> list, Deque<Integer> path, TreeNode node) { if (node == null) { return; }
path.add(node.val);
if (node.left == null && node.right == null) { list.add(pathToString(path)); }
dfs(list, path, node.left); dfs(list, path, node.right); path.removeLast(); }
private String pathToString(Deque<Integer> path) { return path.stream().map(String::valueOf).collect(Collectors.joining("->")); } }
|