Path Sum II 二叉树求和

来源:互联网 发布:徐老师的淘宝店怎么进 编辑:程序博客网 时间:2024/05/13 22:21

Path Sum II

 

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 and sum = 22,
              5             / \            4   8           /   / \          11  13  4         /  \    / \        7    2  5   1

return

[   [5,4,11,2],   [5,8,4,5]]
/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<vector<int> > pathSum(TreeNode *root, int sum) {                vector<vector<int>> res;        vector<int> path;        if(root==NULL)            return res;        solve(res,path,root,sum,0);        return res;    }        void solve(vector<vector<int>> &res, vector<int> &path, TreeNode* root,int sum,int cur)    {                if(root==NULL)            return ;        cur+=root->val;        path.push_back(root->val);        if(cur==sum&&root->left==NULL&&root->right==NULL)            res.push_back(path);        solve(res,path,root->left,sum,cur);        solve(res,path,root->right,sum,cur);        path.pop_back();        cur-=root->val;        return ;    }};
0 0
原创粉丝点击