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

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

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;
    }
};
全部评论

相关推荐

程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
今天 14:10
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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