We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
给出一棵二叉树,其上每个结点的值都是 0 或 1 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数 01101,也就是 13 。
0
1
0 -> 1 -> 1 -> 0 -> 1
01101
13
对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。
以 10^9 + 7 为模,返回这些数字之和。
10^9 + 7
Input: [1,0,1,0,1,0,1] Output: 22 Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
1000
2^31 - 1
The text was updated successfully, but these errors were encountered:
/** * 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(); } };
Sorry, something went wrong.
No branches or pull requests
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
.The text was updated successfully, but these errors were encountered: