Description
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example
1 | root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 |
Solution 1:
Time complexity: O(n^2) => for each node, traverse its subtree, and there are n
nodes => n^2
For each node, we treat it as the starting node as the path, and count how many paths starting from it.
- we need to call
pathSum()
for every node in the tree; - we also need to count how many satisfied paths starting from current node
dfs()
1 | let pathSum = function(root, sum) { |
Solution 2:
Time complexity: O(n)
All the satisfied paths must be encountered when we traversal all the paths from root using dfs.
- while doing DFS, we can make use of the current path, to check if there is a satisfied path on it.
- The checking process is like “LC560. subarray sum equals k”,
- we maintain
a map of <prefixSum, freq>
- for current node, we check if map has
counterpart = curSum+node.val - sum
- after finishing the visit of current node (i.e. done the visits of its children), we decrease its
freq
- we maintain
1 | let pathSum = function(root, sum) { |