Similar to the previous question, this is to record each path and return the result.
Given the below binary tree sum = 22
and,
5 / 4 8 / / / 4 / \ / 7 2 5 1
Return
[ [5,4,11,2], [5,8,4,5]]
We use a sub-function to recursively record, know the leaf node to determine whether there is a value, some words on the record. It is important to note that the left subtree is removed (see note) before the recursive right subtree.
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: voidPathsum (TreeNode *root, vector<vector<int> > &ans, vector<int> tmp,intSubsum,intsum) { if(!root)return ; if(!root, left &&!root, right && subsum + root, val = =sum) {Tmp.push_back (Root-val); Ans.push_back (TMP); } if(Root-Left ) {Tmp.push_back (Root-val); Subsum+ = rootVal; Pathsum (Root-Left , ans, tmp, subsum, sum); Tmp.pop_back (); //because you don't need the left subtree when judging the right subtree.Subsum-= rootVal; } if(Root-Right ) {Tmp.push_back (Root-val); Subsum+ = rootVal; Pathsum (Root-Right , ans, tmp, subsum, sum); }} vector<vector<int> > Pathsum (TreeNode *root,intsum) {Vector<vector<int> >ans; Vector<int>tmp; Pathsum (root, ans, tmp,0, sum); returnans; }};
In fact, the more efficient is the TMP incoming reference, such as Vector<int> &tmp, then each time the record results or left and right recursion after a pop value to ensure that TMP meets the current requirements: see
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: voidPathsum (TreeNode *root, vector<vector<int> > &ans, vector<int> &tmp,intSubsum,intsum) { if(!root)return ; if(!root, left &&!root, right && subsum + root, val = =sum) {Tmp.push_back (Root-val); Ans.push_back (TMP); Tmp.pop_back (); //Keep TMP } if(Root-Left ) {Tmp.push_back (Root-val); Subsum+ = rootVal; Pathsum (Root-Left , ans, tmp, subsum, sum); Tmp.pop_back (); //because you don't need the left subtree when judging the right subtree.Subsum-= root-val;//ditto } if(Root-Right ) {Tmp.push_back (Root-val); Subsum+ = rootVal; Pathsum (Root-Right , ans, tmp, subsum, sum); Tmp.pop_back (); //Keep TMP}} Vector<vector<int> > Pathsum (TreeNode *root,intsum) {Vector<vector<int> >ans; Vector<int>tmp; Pathsum (root, ans, tmp,0, sum); returnans; }};
Leetco Path Sum II