- Binary Tree Paths
Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1. 1
2. / \
3. 2 3
4. \
5. 5
All root-to-leaf paths are:
1. ["1->2->5", "1->3"]
Solution:
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
12. List
13. helper(root, new ArrayList
14. return res;
15. }
16. 17. void helper(TreeNode root, List
18. if (root == null) return;
19. 20. sol.add(root.val);
21. 22. if (root.left == null && root.right == null) {
23. res.add(convert(sol));
24. } else {
25. helper(root.left, sol, res);
26. helper(root.right, sol, res);
27. }
28. 29. sol.remove(sol.size() - 1);
30. }
31. 32. String convert(List
33. StringBuilder sb = new StringBuilder();
34. 35. for (int i = 0; i < list.size(); i++) {
36. if (i > 0) sb.append("->");
37. sb.append(list.get(i));
38. }
39. 40. return sb.toString();
41. }
42. }
