【剑指offer】面试题34. 二叉树中和为某一值的路径

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;
    }
};

解题思路

image.png
二叉树的先序遍历的变形,也可以说是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();
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值