Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 2b9bfb2

Browse files
committed
Add solution #1022
1 parent 8594f38 commit 2b9bfb2

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 1022. Sum of Root To Leaf Binary Numbers
3+
* https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/
4+
* Difficulty: Easy
5+
*
6+
* You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf
7+
* path represents a binary number starting with the most significant bit.
8+
*
9+
* For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary,
10+
* which is 13.
11+
*
12+
* For all leaves in the tree, consider the numbers represented by the path from the root to that
13+
* leaf. Return the sum of these numbers.
14+
*
15+
* The test cases are generated so that the answer fits in a 32-bits integer.
16+
*/
17+
18+
/**
19+
* Definition for a binary tree node.
20+
* function TreeNode(val, left, right) {
21+
* this.val = (val===undefined ? 0 : val)
22+
* this.left = (left===undefined ? null : left)
23+
* this.right = (right===undefined ? null : right)
24+
* }
25+
*/
26+
/**
27+
* @param {TreeNode} root
28+
* @return {number}
29+
*/
30+
var sumRootToLeaf = function(root) {
31+
return dfs(root);
32+
};
33+
34+
function dfs(node, str = '') {
35+
if (!node) return 0;
36+
str += node.val;
37+
if (!node.left && !node.right) {
38+
return parseInt(str, 2)
39+
}
40+
return dfs(node.left, str) + dfs(node.right, str);
41+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@
174174
997|[Find the Town Judge](./0997-find-the-town-judge.js)|Easy|
175175
1009|[Complement of Base 10 Integer](./1009-complement-of-base-10-integer.js)|Easy|
176176
1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium|
177+
1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy|
177178
1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy|
178179
1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium|
179180
1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy|

0 commit comments

Comments
 (0)