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

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

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

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

    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val, left, right) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.left = (left===undefined ? null : left)
    6. * this.right = (right===undefined ? null : right)
    7. * }
    8. */
    9. /**
    10. * @param {TreeNode} root
    11. * @return {string[]}
    12. */
    13. var binaryTreePaths = function (root) {
    14. let res = [];
    15. const traverse = (root, path) => {
    16. if (!root) return;
    17. // root是叶子节点时
    18. if (root.left === null && root.right === null) {
    19. // 加入当前节点
    20. path += root.val;
    21. res.push(path);
    22. return;
    23. }
    24. // 前序遍历位置, 处理非叶子节点,要加箭头
    25. path += root.val + '->';
    26. // 递归遍历左右子树
    27. traverse(root.left, path);
    28. traverse(root.right, path);
    29. }
    30. traverse(root, '');
    31. return res
    32. console.log(res)
    33. };

    image.png