Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 7200200

Browse files
committedJan 31, 2025
Add solution #129
1 parent 0eaa04d commit 7200200

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,7 @@
133133
125|[Valid Palindrome](./0125-valid-palindrome.js)|Easy|
134134
127|[Word Ladder](./0127-word-ladder.js)|Hard|
135135
128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium|
136+
129|[Sum Root to Leaf Numbers](./0129-sum-root-to-leaf-numbers.js)|Medium|
136137
131|[Palindrome Partitioning](./0131-palindrome-partitioning.js)|Medium|
137138
133|[Clone Graph](./0133-clone-graph.js)|Medium|
138139
134|[Gas Station](./0134-gas-station.js)|Medium|
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 129. Sum Root to Leaf Numbers
3+
* https://leetcode.com/problems/sum-root-to-leaf-numbers/
4+
* Difficulty: Medium
5+
*
6+
* You are given the root of a binary tree containing digits from 0 to 9 only.
7+
*
8+
* Each root-to-leaf path in the tree represents a number.
9+
*
10+
* - For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.
11+
*
12+
* Return the total sum of all root-to-leaf numbers. Test cases are generated
13+
* so that the answer will fit in a 32-bit integer.
14+
*
15+
* A leaf node is a node with no children.
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 sumNumbers = function(root) {
31+
function traverse(node, value) {
32+
if (!node) {
33+
return null;
34+
}
35+
value += node.val;
36+
if (!node.left && !node.right) {
37+
return Number(value);
38+
}
39+
return traverse(node.left, value) + traverse(node.right, value);
40+
}
41+
42+
return traverse(root, '');
43+
};

0 commit comments

Comments
 (0)
Please sign in to comment.