leetcode 437. 路径总和 III
暴力双搜
复杂度 O(n^2)
class Solution {
public:
int dfs(TreeNode* root,int q)
{
if(!root)return 0;
int res=0;
if(root->val==q)res++;
res+=dfs(root->left,q-root->val);
res+=dfs(root->right,q-root->val);
return res;
}
int pathSum(TreeNode* root, int q) {
if(!root)return 0;
int res=dfs(root,q);
res+=pathSum(root->left,q);
res+=pathSum(root->right,q);
return res;
}
};
哈希表+前缀和+dfs
复杂度O(n)
class Solution {
public:
unordered_map<int,int>hash;
int res=0;
int dfs(TreeNode* root,int q,int cur){
if(!root)return 0;
cur+=root->val;
res+=hash[cur-q];
hash[cur]++;
dfs(root->left,q,cur);
dfs(root->right,q,cur);
hash[cur]--;
return res;
}
int pathSum(TreeNode* root, int q) {
if(!root)return 0;
hash[0]=1;
dfs(root,q,0);
return res;
}
};
leetcode 113. 路径总和 II
class Solution {
public:
vector<vector<int>>res;
vector<int>path;
vector<vector<int>> pathSum(TreeNode* root, int q) {
if(!root)return res;
dfs(root,q);
return res;
}
void dfs(TreeNode* root,int q)
{
path.push_back(root->val);
if(!root->left&&!root->right)
{
if(root->val==q)res.push_back(path);
return ;
}
if(root->left){dfs(root->left,q-root->val);path.pop_back();}
if(root->right){dfs(root->right,q-root->val);path.pop_back();}
}
};
|