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:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
Return 3. The paths that sum to 8 are:
- 5 -> 3
- 5 -> 2 -> 1
- -3 -> 11
解法1:DFS / Recursion
这题考察DFS的基本知识。因为考虑的是每一个从上到下的path,那么应该要想到要用DFS。
对于每一个节点,如果包括自己,则可以递归运算left 和right,而要match的数则变成了sum - val。
如果不包括自己,则直接运算left和right,最后将两个情况相加就是结果。
实际上这里就是用了一个preorder遍历,回想一下preorder的算法:
visit root;
visit left;
visit right;
这里也一样:
visit root => compute number of paths with root (dfs(root, sum))
visit left => compute number of paths with left (pathSum(root->left, sum))
visit right => compute number of paths with right (pathSum(root->right, sum))
C++
Java