题目描述
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.
例子
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
1
2
3
4
5
6
7 10
/ \
5 -3
/ \ \
3 2 11
/ \ \
>3 -2 1Return 3. The paths that sum to 8 are:
- 5 -> 3
- 5 -> 2 -> 1
- -3 -> 11
解题思路
方法一
可以用一个变量来维护从 root
到当前节点的和,再递归的以所有节点为 root
进行遍历,代码如下:
1 | /** |
- 时间复杂度: O(n^2)
- 空间复杂度: O(n)
方法二
第一种方法本质上可以转换成判断两条路径,一个是从 root
到 节点 i
, 一条是从 root
到节点 j
(必须要经过 i
),计算这两条路径的和(前缀和 prefix
)并相减就可以知道从 i
到 j
的和;根据这个思路,如果我们只用一次遍历树,并记录从 root
到当前节点 i
的和,那么问题就转换成,在 j
之前有多少个节点 i
满足 prefix(i) = prefix(j) - target
,根据这个思路,我们可以用一个哈希表来存储所有节点的 prefix
,这样就不需要递归遍历,注意一下当遍历完当前子树的时候应该将当前子树的所有 prefix
从哈希表删掉,不然会影响其他子树的结果,代码如下:
1 | /** |
- 时间复杂度: O(n)
- 空间复杂度: O(h) -> 只跟树的最大高度有关,因为哈希表不会同时存放左右两个子树的值