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 1return
[ [5,4,11,2], [5,8,4,5] ]
思路:递归。用完某个node之后记得把值pop出来。
- void findpath(TreeNode *root, int sum, vector<vector<int>> &res, vector<int> &path){
- if(!root->left && !root->right){
- if(sum == 0) res.push_back(path);
- return;
- }
- if(root->left){
- path.push_back(root->left->val);
- findpath(root->left, sum - root->left->val, res, path);
- path.pop_back();
- }
- if(root->right){
- path.push_back(root->right->val);
- findpath(root->right, sum - root->right->val, res, path);
- path.pop_back();
- }
- }
- vector<vector<int> > pathSum(TreeNode *root, int sum) {
- vector<vector<int>> res;
- vector<int> path;
- if(!root) return res;
- path.push_back(root->val);
- findpath(root, sum - root->val, res, path);
- return res;
- }
No comments:
Post a Comment