File tree Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change 133
133
125|[ Valid Palindrome] ( ./0125-valid-palindrome.js ) |Easy|
134
134
127|[ Word Ladder] ( ./0127-word-ladder.js ) |Hard|
135
135
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|
136
137
131|[ Palindrome Partitioning] ( ./0131-palindrome-partitioning.js ) |Medium|
137
138
133|[ Clone Graph] ( ./0133-clone-graph.js ) |Medium|
138
139
134|[ Gas Station] ( ./0134-gas-station.js ) |Medium|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments