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] ]
----------based on Path Sum
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void ps (TreeNode *root, int sum, int curSum, vector<int> curV, vector<vector<int> > &re) { if (root != NULL) { curSum += root->val; curV.push_back(root->val); if (root->left == NULL && root->right == NULL) { if (curSum == sum) { re.push_back(curV); } }else { ps(root->left,sum,curSum,curV,re); ps(root->right,sum,curSum,curV,re); } } } vector<vector<int> > pathSum(TreeNode *root, int sum) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<int> path; vector<vector<int> > paths; ps(root,sum,0,path,paths); return paths; } };
优化了下用于暂时储存的vector,此法可用于若干种类似题目
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void helper(TreeNode *root,int sum, vector<vector<int> > &rt, vector<int> &cur) { if (root == NULL) return; if (root->val == sum && root->left == NULL && root->right == NULL) { vector<int> t = cur; t.push_back(root->val); rt.push_back(t); return; } cur.push_back(root->val); helper(root->left,sum - root->val,rt,cur); helper(root->right,sum - root->val,rt,cur); cur.pop_back(); } vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int> > rt; vector<int> cur; helper(root,sum,rt,cur); return rt; } };
No comments:
Post a Comment