ntree.ai

Path Sum

mediumsolvedattempted

Given the root of a binary tree and an integer target, return the number of paths whose values add up to target.

A path does not need to start at the root or end at a leaf, but it should be from parent to its child.

Example 1:

10
5
3
3
-2
2
1
-3
11
Input:  root = [10, 5, -3, 3, 2, null, 11, 3, -2, null, 1], target = 8
Output: 3
Explanation: 5 + 3 = 8, 5 + 2 + 1 = 8, and -3 + 11 = 8.

Example 2:

5
4
11
7
2
8
13
4
5
1
Input:  root = [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1], target = 22
Output: 3
Explanation: 5 + 4 + 11 + 2 = 22, 5 + 8 + 4 + 5 = 22, and 4 + 11 + 7 = 22.

Constraints:

  • 0 <= number of nodes <= 1000
  • -10^9 <= Node.val <= 10^9
  • -1000 <= target <= 1000
# Definitions:
# class BinaryTreeNode:
# def __init__(self, val=0):
# self.val = val
# self.left = None
# self.right = None
 
def pathSum(root: BinaryTreeNode, target: int) -> int:
pass
 
10
5
3
3
-2
2
1
-3
11

Press Visualise to step through your code.