leetcode 437. 路径总和 III
题目链接
暴力双搜
复杂度 O(n^2)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
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)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
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
题目链接
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
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();}
}
};
这篇博客探讨了LeetCode中的两道题目,437路径总和III和113路径总和II。首先介绍了暴力双搜索方法,虽然其复杂度为O(n^2),然后提出哈希表结合前缀和的解决方案,将复杂度降低到O(n)。在路径总和III中,通过维护哈希表记录当前路径和,优化了DFS搜索。而在路径总和II中,利用路径存储和回溯找到所有路径。这些优化技巧对于解决二叉树问题非常有用。
577

被折叠的 条评论
为什么被折叠?



