AcWing 47. 二叉树中和为某一值的路径
原题链接
中等
作者:
葱花鸡蛋
,
2020-03-24 22:35:42
,
所有人可见
,
阅读 577
//0045二叉树中和为某一数的路径
//错误代码:会重复访问路径,问题在子节点的判断
//这样的访问没得救
class Solution {
public:
vector<int>buff;
vector<vector<int>>ans;
void Dfs(TreeNode *root,int cur, int target)
{
//每个叶子结点都有空的左右节点,所以不能这样判断叶子节点:这是叶节点的左右儿子
//所以会两次访问
if (root == NULL) {
if (cur == target) {
ans.push_back(buff);
}
return;
}
buff.push_back(root -> val);
Dfs(root -> left, cur + root -> val, target);
Dfs(root -> right, cur + root -> val, target);
buff.pop_back();
}
vector<vector<int>> findPath(TreeNode* root, int sum) {
buff.clear();
ans.clear();
if (root == NULL) return ans;
Dfs(root, 0, sum);
ans.erase(unique(ans.begin(), ans.end()), ans.end());
return ans;
}
};
//正确的
class Solution {
public:
vector<int>buff;
vector<vector<int>>ans;
void Dfs(TreeNode *root,int cur)
{
if (root == NULL) return;
cur -= root -> val;
buff.push_back(root -> val);
if (!root -> left && !root -> right && !cur) ans.push_back(buff);
Dfs(root -> left, cur);
Dfs(root -> right, cur);
buff.pop_back();
}
vector<vector<int>> findPath(TreeNode* root, int sum) {
buff.clear();
ans.clear();
Dfs(root, sum);
return ans;
}
};