您的位置:首页 > 其它

437. Path Sum III

2018-01-07 06:00 363 查看
1. Description

Given a binary tree, find the number of paths that sum to a given value.

2. Solution

The answer include three parts, the number of paths from left-child tree, the number of paths from right-child tree,

and the number of paths from the root.

How to calculate the number of paths from the root?

Use a value named current to store the current sum, when the path pass the root, add root's value to current.

Use recursive way to calculate the number.

3. Code

int pathSum(TreeNode* root, int sum) {
if(root==NULL) return 0;
return pathSum(root->left,sum) + pathSum(root->right,sum) + sumUp(root,0,sum);
}
int sumUp(TreeNode* root, int pre, int& sum){
if(!root) return 0;
int current = pre + root->val;
return (current == sum) + sumUp(root->left, current, sum) + sumUp(root->right, current, sum);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Tree