给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。

    叶子节点 是指没有子节点的节点。


    示例 1:
    image.png

    输入:root = [1,2,3,null,5]
    输出:[“1->2->5”,”1->3”]
    示例 2:

    输入:root = [1]
    输出:[“1”]

    提示:

    树中节点的数目在范围 [1, 100] 内
    -100 <= Node.val <= 100


    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode() {}
    8. * TreeNode(int val) { this.val = val; }
    9. * TreeNode(int val, TreeNode left, TreeNode right) {
    10. * this.val = val;
    11. * this.left = left;
    12. * this.right = right;
    13. * }
    14. * }
    15. */
    16. class Solution {
    17. public List<String> binaryTreePaths(TreeNode root) {
    18. List<String> res = new ArrayList<>();
    19. dfs(root, res, new String());
    20. return res;
    21. }
    22. void dfs(TreeNode root, List<String> res, String s) {
    23. if (root == null) return;
    24. s = s + String.valueOf(root.val);
    25. if (root.left == null && root.right == null) {
    26. res.add(s);
    27. return;
    28. } else {
    29. s = s + "->";
    30. dfs(root.left, res, s);
    31. dfs(root.right, res, s);
    32. }
    33. }
    34. }