路徑總和 III
此題和 112路徑和 的區別點在於起點和終點都不確定,難點也在於此。
- 終點不確定如何解決?
遍歷一整棵子樹,搜索過程中只要路徑和滿足要求,答案加1 - 起點不確定如何解決?
既然起點不確定,那就分別每個節點作爲搜索的起點。
所以實際上這個題目由兩重遞歸組成,對二叉樹中的每個節點都作爲搜索起點,求路徑和。
時間複雜度:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
if(!root) return 0;
return helper(root,sum)+pathSum(root->left,sum)+pathSum(root->right,sum);
}
int helper(TreeNode *root,int sum){
if(!root) return 0;
sum -= root->val;
return !sum+helper(root->left,sum)+helper(root->right,sum);
}
};
另一種風格,不返回值,參數帶一個引用。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
if(!root){
return 0;
}
int res = 0 ;
helper(root,sum,res);
return res+pathSum(root->left,sum)+pathSum(root->right,sum);
}
void helper(TreeNode* root,int sum,int &res){
if(!root){
return;
}
if(sum==root->val){
res++;
}
if(root->left){
helper(root->left,sum-root->val,res);
}
if(root->right){
helper(root->right,sum-root->val,res);
}
}
};