思路:定义两个队列,一个用来放节点,一个用来放当前节点表示的数,遍历节点,直到每个节点到达叶节点为该条路径的最后值,每到达一个叶节点, 就把值给到和的变量sum累加
算法思想: 队列
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var sumNumbers = function(root) {
if(root === null) return 0;
let queue_node = [root];
let queue_num = [root.val];
let sum = 0;
while(queue_node.length > 0){
let node = queue_node.shift();
let num = queue_num.shift();
if(node.left === null && node.right === null){
sum += num;
} else {
if(node.left){
queue_node.push(node.left);
queue_num.push(10*num + node.left.val);
console.log(num, node.left.val);
}
if(node.right){
queue_node.push(node.right);
queue_num.push(10*num + node.right.val);
}
}
}
return sum;
};
网友评论