Open Tcdian opened 3 years ago
/**
* 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) {
let sum = 0;
const path = [];
dfs(root);
return sum;
function dfs(root) {
if (root === null) {
return;
}
path.push(root.val);
if (root.left === null && root.right === null) {
sum += parseInt(path.join(''), 2);
}
dfs(root.left);
dfs(root.right);
path.pop();
}
};
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function sumRootToLeaf(root: TreeNode | null): number {
let sum = 0;
const path: number[] = [];
dfs(root);
return sum;
function dfs(root: TreeNode | null) {
if (root === null) {
return;
}
path.push(root.val);
if (root.left === null && root.right === null) {
sum += parseInt(path.join(''), 2);
}
dfs(root.left);
dfs(root.right);
path.pop();
}
};
1022. Sum of Root To Leaf Binary Numbers
给出一棵二叉树,其上每个结点的值都是
0
或1
。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。例如,如果路径为0 -> 1 -> 1 -> 0 -> 1
,那么它表示二进制数01101
,也就是13
。对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。
以
10^9 + 7
为模,返回这些数字之和。Example
Note
1
and1000
.0
or1
.2^31 - 1
.