2020.7.9更新
解题思路
算法流程:
1.将当前结点加入到path中,currentSum加上该结点的值
2.如果此时currentSum==expectSum且该结点为叶子结点,说明找到路径,保存下来
3.如果不是叶子结点,则在其左子树和右子树中分别去找
4.在返回到父节点之前,在路径上删除结点,并在currentSum中减去当前结点的值
代码
class Solution {
public:
std::vector<std::vector<int>> ans;
std::vector<std::vector<int>> pathSum(TreeNode* root, int sum) {
if (root == nullptr) return ans;
std::vector<int> path;
int currentSum = 0;
FindPath(root, sum, path, currentSum);
return ans;
}
void FindPath(TreeNode* root, int expectedSum, std::vector<int>& _path, int& currentSum) {
currentSum += root->val;
_path.push_back(root->val);
//如果是叶结点,并且路径上结点的和等于输入的值
//保存这条路径
bool isLeaf = root->left == nullptr && root->right == nullptr;
if (isLeaf && expectedSum == currentSum) ans.push_back(_path);
//如果不是叶结点,则遍历它的叶子结点
if (root->left != nullptr) FindPath(root->left, expectedSum, _path, currentSum);
if (root->right != nullptr) FindPath(root->right, expectedSum, _path, currentSum);
//在返回到父节点之前,在路径上删除当前结点
_path.pop_back();
//并在currentSum中减去当前结点的值
currentSum -= root->val;
}
};
解题思路
二叉树的先序遍历的变形,也可以说是DFS
代码
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res;
if(root==NULL) return res;
vector<int> path;//使用vector作栈,使用它作栈来实现后进能够先出
FindPath(root, res, path, sum, 0);
return res;
}
void FindPath(TreeNode* root, vector<vector<int>>& res,vector<int>& path,int expectedSum, int currentSum)
{
currentSum += root->val;
path.push_back(root->val);
bool isLeaf=(root->left == NULL&&root->right==NULL);
if (currentSum==expectedSum&&isLeaf)//如果当前值与给出的值相等,且该结点为叶子节点,则
{
res.push_back(path);//该路径入栈
}
if (root->left != NULL) FindPath(root->left, res, path, expectedSum, currentSum);
if (root->right != NULL) FindPath(root->right, res, path, expectedSum, currentSum);
//返回父节点之前,在路径上删除当前结点
path.pop_back();
}
};