path-sum-ii

来源:互联网 发布:淘宝买的手机如何保修 编辑:程序博客网 时间:2024/06/14 15:21

题目:

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
For example:
Given the below binary tree andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]

程序:

class Solution {public:    vector<vector<int> > pathSum(TreeNode *root, int sum) {        vector<vector<int>> res;        if(root==NULL)            return res;        solve(res,root,sum);        return res;    }    void solve(vector<vector<int>> &res,TreeNode *root,int sum)    {        if(root&&root->left==NULL&&root->right==NULL&&sum==root->val)        {            v.push_back(root->val);            res.push_back(v);            v.pop_back();            return;        }        if(root==NULL)            return;        v.push_back(root->val);        solve(res,root->left,sum-root->val);        solve(res,root->right,sum-root->val);        v.pop_back();    }    vector<int> v;};
原创粉丝点击