/**
* 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;
}
var totalSum = 0;
findNum(root,0);
return totalSum;
function findNum(node,curSum){
curSum = node.val + curSum*10;
var left = node.left;
var right = node.right;
if(left === null && right === null){
totalSum += curSum;
return;
}
if(left !== null){
findNum(node.left,curSum);
}
if(right !== null){
findNum(node.right,curSum);
}
}
};
这道题目使用递归或者栈都可以解决。
我比较习惯用递归:递归代码看上去比较简洁,逻辑也更清楚。