孙晓聪
  • 最新
  • 博客
  • 书评
  • Path Sum II

    Description

    doc

    Solutions

    First Idea

    /**
     * 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
     * @param {number} targetSum
     * @return {number[][]}
     */
    var pathSum = function (root, targetSum) {
      if (root === null) {
        return []
      }
    
      const leftVal = targetSum - root.val
      if (root.left === null && root.right === null) {
        return leftVal ? [] : [[root.val]]
      }
    
      const left = pathSum(root.left, leftVal)
      const right = pathSum(root.right, leftVal)
    
      return [...left, ...right].map((v) => [root.val, ...v])
    }
    
    • Time Complexity: O(n)
    • Space Complexity: O(n)

    BFS

    /**
     * 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
     * @param {number} targetSum
     * @return {number[][]}
     */
    var pathSum = function (root, targetSum) {
      if (root === null) {
        return []
      }
    
      root.vals = [root.val]
      let queue = [root]
      let result = []
    
      while (queue.length) {
        const cur = queue.shift()
    
        if (cur.left === null && cur.right === null && cur.val === targetSum) {
          result.push(cur.vals)
          continue
        }
    
        if (cur.left) {
          cur.left.vals = [...cur.vals, cur.left.val]
          cur.left.val += cur.val
          queue.push(cur.left)
        }
    
        if (cur.right) {
          cur.right.vals = [...cur.vals, cur.right.val]
          cur.right.val += cur.val
          queue.push(cur.right)
        }
      }
    
      return result
    }
    
    • Time Complexity: O(n)
    • Space Complexity: O(nlogn)