Instructions
You are given the root of a binary tree and a whole number k. Node values can be negative.
A downward path starts at any node and goes down to one of its descendants, moving from a parent to a child at each step. A single node is also a downward path. A path never goes up.
Return how many downward paths have node values that add up to exactly k. Two paths are different when they have a different first node or a different last node. If the tree is empty, return 0.
How the input is shown
The tree is written in level order: the values row by row, from left to right, with null where a child is missing. For example, [1, 2, 3, null, 4] is the root 1 with children 2 and 3, and 4 is the right child of 2. Your function gets the TreeNode root (or null / None for an empty tree), with fields val, left and right, and the number k.
Hint
Walk down from the root and keep the running sum from the root to the current node. A path that ends at the current node adds up to k when the running sum at some node above it (or the empty start, 0) equals running sum - k. Keep a count of the running sums on the current root-to-node path in a hash map, and remove the current one when you go back up.
Examples
Example 1
- Input:
- [6,2,-3,4,-2,null,9], 6
- Output:
- 4
Four downward paths add up to 6: the single node 6; 2 -> 4; 6 -> 2 -> -2 (6 + 2 - 2 = 6); and -3 -> 9. Paths such as 6 -> -3 -> 9 (12) or 2 -> -2 (0) do not count.
Example 2
- Input:
- [1,-1,1,1,null,-1], 0
- Output:
- 3
Three downward paths add up to 0: the root 1 with its left child -1; that -1 with its child 1; and the right child 1 with its child -1. A path such as 1 -> -1 -> 1 adds up to 1, so it does not count.
Example 3
- Input:
- [], 5
- Output:
- 0
The tree is empty, so there are no paths at all.
Constraints
- The tree has between
0and40nodes. -10 <= Node.val <= 10-30 <= k <= 30
3 examples run when you press Run. Submit checks every hidden test too.
- Input:
- [6,2,-3,4,-2,null,9], 6
- Expected:
- 4
- Input:
- [1,-1,1,1,null,-1], 0
- Expected:
- 3
- Input:
- [], 5
- Expected:
- 0
Run checks your code against the 3 examples. Submit checks it against all 163 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.