Skip to content
On this page

113. Path Sum II

https://leetcode.com/problems/path-sum-ii/

js
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} sum
 * @return {number[][]}
 */
function pathSum(root, sum) {
  const result = []
  calcSum(root, sum, [], result)
  return result
}

function calcSum(root, sum, nums, result) {
  if (!root) {
    return
  }

  if (root.val === sum && !root.left && !root.right) {
    result.push([...nums, root.val])
  }

  if (root.left) {
    calcSum(root.left, sum - root.val, nums.concat([root.val]), result)
  }

  if (root.right) {
    calcSum(root.right, sum - root.val, nums.concat([root.val]), result)
  }
}
py
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Solution(object):

    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        result = []
        self.calcSum(root, sum, [], result)
        return result

    def calcSum(self, root, sum, nums, result):
        if not root:
            return
        if root.val == sum and not root.left and not root.right:
            result.append(nums + [root.val])
        if root.left:
            self.calcSum(root.left, sum - root.val, nums + [root.val], result)
        if root.right:
            self.calcSum(root.right, sum - root.val, nums + [root.val], result)
go
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func pathSum(root *TreeNode, sum int) [][]int {
	result := [][]int{}
	calcSum(root, sum, []int{}, &result)
	return result
}

func calcSum(root *TreeNode, sum int, nums []int, result *[][]int) {
	if root == nil {
		return
	}

	nums = append(nums, root.Val)

	if root.Val == sum && root.Left == nil && root.Right == nil {
		*result = append(*result, nums)
	}

	if root.Left != nil {
		calcSum(root.Left, sum-root.Val, append([]int{}, nums...), result)
	}

	if root.Right != nil {
		calcSum(root.Right, sum-root.Val, append([]int{}, nums...), result)
	}
}