题解 | #二叉树中和为某一值的路径(二)#

二叉树中和为某一值的路径(二)

http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    void dfs(TreeNode* root, int expectNumber, vector<vector<int>>& res, vector<int> ans, int num) {
        if(!root)
            return;
        ans.push_back(root->val);
        num += root->val;
        if(!root->left && !root->right) {
            if(num == expectNumber) {
                res.push_back(ans);
                num -= ans.back();
                ans.pop_back();
            }
            return;
        }
        dfs(root->left, expectNumber, res, ans, num);
        dfs(root->right, expectNumber, res, ans, num);
    }
    vector<vector<int>> FindPath(TreeNode* root,int expectNumber) {
        vector<vector<int>> res;
        vector<int> ans;
        int num = 0;
        dfs(root, expectNumber, res, ans, num);
        return res;
    }
};
全部评论

相关推荐

牛客38347925...:9,2学生暑期实习失利开始投小厂,给这群人整自信了
点赞 评论 收藏
分享
找到实习了&nbsp;给了150一天&nbsp;但是说是低代码&nbsp;值得去吗
码农索隆:是在没实习,可去,待个一两周,不行就润呗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务