437. Path Sum III*
https://leetcode.com/problems/path-sum-iii/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:
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:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
C++ 实现 1
给定一个二叉树和一个整数 sum, 求出这个二叉树中所有路径上节点的和等于 sum 的条数.
这道题与 112. Path Sum*, 113. Path Sum II** 中关于路径的定义不同, 前两题是要求从根节点到叶子节点, 而这里的路径定义为从任意的节点到它下面任意的节点, 也就是说起始节点不必为根节点, 终止节点不必为叶子节点, 但要保证路径是从上到下的.
关于这道题的思路: 是要分情况讨论, 我先给出函数接口, int pathSum(TreeNode* root, int sum)
, 它返回路径的条数. 分两种情况, 一种是这条路径包含 root, 另一种是并不包含 root. 当不包含 root 时, 情况稍微简单, 即 pathSum(root->left, sum) + pathSum(root->right, sum)
, 即只要在左右子树找和为 sum 的路径即可. 而当包含 root 时, 需要设置额外的函数处理这种情况: pathWithRoot(root, sum)
, 如果 root 的值刚好等于 sum, 仍然要考虑是左右子树是否存在路径和为 sum - root->val
, 但此时由于 root 刚好等于 sum, 这就相当于有了 1 条路径. 如果 root 的值不等于 sum, 那么就要判断左右子树的路径和是否等于 sum - root->val
.
class Solution {
private:
// (root->val == sum ? 1 : 0) 中的数字 1 就是累加了 root 的
// 值刚好等于 sum 的情况.
int pathWithRoot(TreeNode *root, int sum) {
if (!root)
return 0;
return (root->val == sum ? 1 : 0) +
pathWithRoot(root->left, sum - root->val) +
pathWithRoot(root->right, sum - root->val);
}
public:
int pathSum(TreeNode* root, int sum) {
if (!root)
return 0;
return pathWithRoot(root, sum) +
pathSum(root->left, sum) +
pathSum(root->right, sum);
}
};