1022. 从根到叶的二进制数之和

给出一棵二叉树,其上每个结点的值都是 0 或 1 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数 01101,也就是 13 。

对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。

返回这些数字之和。题目数据保证答案是一个 32 位 整数。

链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var sumRootToLeaf = function(root) {
const paths: string[] = []
function findPath(node: TreeNode, path: string) {
if (node === null) return
path += node.val.toString()
if (!node.left && !node.right) {
paths.push(path)
return
}
findPath(node.left, path)
findPath(node.right, path)
}
findPath(root, "")
return paths.reduce((pre, data) => {
pre += parseInt(data, 2)
return pre
}, 0)
};