Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

求根到叶子节点数字之和-129 #60

Open
sl1673495 opened this issue Jun 7, 2020 · 0 comments
Open

求根到叶子节点数字之和-129 #60

sl1673495 opened this issue Jun 7, 2020 · 0 comments
Labels
DFS 深度优先遍历 二叉树

Comments

@sl1673495
Copy link
Owner

给定一个二叉树,它的每个结点都存放一个 0-9 的数字,每条从根到叶子节点的路径都代表一个数字。

例如,从根到叶子节点路径 1->2->3 代表数字 123。

计算从根到叶子节点生成的所有数字之和。

说明: 叶子节点是指没有子节点的节点。

示例 1:

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

示例 2:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-root-to-leaf-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

先按照字符串拼接的思路用 DFS 收集所有到达叶子节点的路径的集合,最后把这些字符串转化为数字求和即可。

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
let sumNumbers = function (root) {
    let paths = []

    let dfs = (node, path) => {
        if (!node) {
            return
        }

        let newPath = `${path}${node.val}`
        if (!node.left && !node.right) {
            paths.push(newPath)
            return
        }

        dfs(node.left, newPath)
        dfs(node.right, newPath)
    }

    dfs(root, '')
    return paths.reduce((total, val) => {
      return total + Number(val) 
    }, 0)
};
@sl1673495 sl1673495 added DFS 深度优先遍历 二叉树 labels Jun 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
DFS 深度优先遍历 二叉树
Projects
None yet
Development

No branches or pull requests

1 participant