给你一个二叉树的根节点 root ,树中每个节点都存放有一个 0 到 9 之间的数字。
    每条从根节点到叶节点的路径都代表一个数字:

    例如,从根节点到叶节点的路径 1 -> 2 -> 3 表示数字 123 。
    计算从根节点到叶节点生成的 所有数字之和 。

    叶节点 是指没有子节点的节点。
    示例 1:

    image.png
    输入:root = [1,2,3]
    输出:25
    解释:
    从根到叶子节点路径 1->2 代表数字 12
    从根到叶子节点路径 1->3 代表数字 13
    因此,数字总和 = 12 + 13 = 25
    示例 2:

    输入:root = [4,9,0,5,1]
    输出:1026
    解释:
    从根到叶子节点路径 4->9->5 代表数字 495
    从根到叶子节点路径 4->9->1 代表数字 491
    从根到叶子节点路径 4->0 代表数字 40
    因此,数字总和 = 495 + 491 + 40 = 1026

    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 {number}
    12. */
    13. var sumNumbers = function (root) {
    14. // 说过二叉树的递归分为「遍历」和「分解问题」两种思维模式,这道题需要用到「遍历」的思维。
    15. const dfs = (root, path) => {
    16. if (root == null) {
    17. return 0;
    18. }
    19. path = path * 10 + root.val;
    20. // 当是叶子节点的时候
    21. if (!root.left && !root.right) {
    22. return path;
    23. }
    24. return dfs(root.left, path) + dfs(root.right, path);
    25. };
    26. return dfs(root, 0);
    27. };

    image.png