新增129. 求根节点到叶节点数字之和版本

This commit is contained in:
jerryfishcode
2021-09-28 00:38:48 +08:00
committed by GitHub
parent 91d01d610c
commit 766af43f4e

View File

@ -241,6 +241,48 @@ class Solution:
Go
JavaScript
```javascript
var sumNumbers = function(root) {
const listToInt = path => {
let sum = 0;
for(let num of path){
// sum * 10 表示进位
sum = sum * 10 + num;
}
return sum;
}
const recur = root =>{
if (root.left == null && root.right == null) {
// 当是叶子节点的时候,开始处理
res += listToInt(path);
return;
}
if (root.left != null){
// 注意有回溯
path.push(root.left.val);
recur(root.left);
path.pop();
}
if (root.right != null){
// 注意有回溯
path.push(root.right.val);
recur(root.right);
path.pop();
}
return;
};
const path = new Array();
let res = 0;
// 如果节点为0那么就返回0
if (root == null) return 0;
// 首先将根节点放到集合中
path.push(root.val);
// 开始递归
recur(root);
return res;
};
```