您的位置:首页 > 其它

437. Path Sum III

2016-10-26 12:24 288 查看
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


【问题分析】

 该问题是path sum和path sum ii的延续,也算是挺容易的

 要求是: 

    1、找到所有和为sum的路径,关键的点是路径不一定是从root到叶子节点,可能是中间某一段

     2、要求输出路径个数,这样就降低了难度

 因此解决问题分解之后就会更加容易处理:

    1、获取以每个节点为起始点,并且和为sum的路径个数,这个相对容易

     2、将每个节点为起始节点的路径个数相加,就是最终结果

【AC代码】

class Solution {
public:
int pathSum(TreeNode* root, int sum) {
int res = 0;
if (root == NULL) {
return 0;
}
//层序遍历树中的节点
std::queue<TreeNode*> cqueue;
cqueue.push(root);
while (!cqueue.empty()) {
TreeNode* node = cqueue.front();
cqueue.pop();

if (node->left)
cqueue.push(node->left);
if (node->right)
cqueue.push(node->right);

res += getPathNum(node, sum); //获取以root为起点的所有路径的个数
}

return res;
}

int getPathNum(TreeNode* root, int sum) { //获取以root为起点,和为sum的所有路径的个数
int res = 0;
if (root == NULL) { //递归结束条件
return 0;
}

//must go to the leaf node //即使找到了和为sum的节点,还要继续遍历叶子节点,因此不是直接返回1,而是res+1
if (root->val == sum) {
res += 1;
}

int val = root->val;
if (root->left) { //访问左孩子
res += getPathNum(root->left, sum - val);
}
if (root->right) { //访问右孩子
res += getPathNum(root->right, sum - val);
}

return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode