剑指offer-二叉树中和为某一路径的和

一、问题描述

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

二、思路

采用递归思想,如果某一路径和为目标值且当前节点是叶子节点,那么将当前路径存入所求的数组中,如果不是,递归遍历左子树和右子树,但是一定要记得如果没有符合结果的路径,一定要将当前的节点弹出。

三、代码

class Solution {
public:
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
		vector<vector<int> > res;
        if(root == NULL) return res;
        vector<int> path;
        int currentSum = 0;
        FindPath(root, expectNumber, path, currentSum, res);
        return res;
    }
    void FindPath(TreeNode* root, int expectNumber, vector<int> path, int currentSum, vector<vector<int> >& res){
        currentSum += root -> val;
        path.push_back(root -> val);
        bool isLeaf = root -> left == NULL && root -> right == NULL;
        if(expectNumber == currentSum && isLeaf){
            res.push_back(path);
        }
        if(root -> left != NULL) FindPath(root -> left, expectNumber, path, currentSum, res);
        if(root -> right != NULL) FindPath(root -> right, expectNumber, path, currentSum, res);
        path.pop_back();
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fullstack_lth

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值