Skip to content

Commit 7900788

Browse files
committed
129. 求根节点到叶节点数字之和
1 parent 7c14129 commit 7900788

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
|119|[杨辉三角 II](https://leetcode.cn/problems/pascals-triangle-ii/)|[JavaScript](./algorithms/pascals-triangle-ii.js)|Easy|
6969
|124|[二叉树中的最大路径和](https://leetcode.cn/problems/binary-tree-maximum-path-sum/)|[JavaScript](./algorithms/binary-tree-maximum-path-sum.js)|Hard|
7070
|125|[验证回文串](https://leetcode.cn/problems/valid-palindrome/)|[JavaScript](./algorithms/valid-palindrome.js)|Easy|
71+
|129|[求根节点到叶节点数字之和](https://leetcode.cn/problems/sum-root-to-leaf-numbers/)|[JavaScript](./algorithms/sum-root-to-leaf-numbers.js)|Medium|
7172
|136|[只出现一次的数字](https://leetcode-cn.com/problems/single-number/)|[JavaScript](./algorithms/single-number.js)|Easy|
7273
|141|[环形链表](https://leetcode-cn.com/problems/linked-list-cycle/)|[JavaScript](./algorithms/linked-list-cycle.js)|Easy|
7374
|142|[环形链表 II](https://leetcode.cn/problems/linked-list-cycle-ii/)|[JavaScript](./algorithms/linked-list-cycle-ii.js)|Medium|
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* 129. 求根节点到叶节点数字之和
11+
* @param {TreeNode} root
12+
* @return {number}
13+
*/
14+
var sumNumbers = function (root) {
15+
let sum = 0;
16+
const dfs = (root, val = 0) => {
17+
if (root) {
18+
val = val * 10 + root.val;
19+
if (!root.left && !root.right) {
20+
sum += val;
21+
}
22+
dfs(root.left, val);
23+
dfs(root.right, val);
24+
}
25+
};
26+
dfs(root);
27+
28+
return sum;
29+
};

0 commit comments

Comments
 (0)