Skip to content

129根叶数字和

code

javascript
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var sumNumbers = function(root) {
    let result = [];
    function test(root, temp){
        if(root === null){
            result.push(temp);
            return;
        }
        temp = temp + root.val;
        if(root.left === null && root.right === null){          
            result.push(temp);
            return;
        }
        if(root.left !== null) {
            test(root.left, temp);
        }
        if(root.right !== null){
            test(root.right, temp);
        }
    }
    test(root, '');
    console.log(result);
    return result.map((item) => Number(item)).reduce((accu, curr) => accu + curr);
};

总结

  1. 我暂时没看太明白这个的逻辑,是说把所有的都写下来然后抓数字加和么
  2. 最后面那个判断的地方比较怪异,但是那么写是ok可以的
  3. 感觉没啥卵用