孙晓聪
  • 最新
  • 博客
  • 书评
  • Sum Root to Leaf Numbers

    Description

    ref

    Solution

    Recursive Solution

    /**
     * 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) {
      function sum(node) {
        if (!node) {
          return []
        }
    
        if (!node.left && !node.right) {
          return [`${node.val}`]
        }
    
        return [...sum(node.left), ...sum(node.right)].map((v) => node.val + v)
      }
    
      return sum(root).reduce((acc, cur) => acc + Number.parseInt(cur), 0)
    }