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] ]
<pre name="code" class="cpp">/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { //理解这些代码关键在于用测试例子进行模拟过程即可 private: vector< vector<int> > ivv;//最终结果 vector<int> cur_iv;//用于保存中间结果 public: vector<vector<int> > pathSum(TreeNode *root, int sum) { if(root==NULL) return ivv; if(root->left==NULL && root->right==NULL) { if(root->val==sum) { cur_iv.push_back(root->val); ivv.push_back(cur_iv); cur_iv.pop_back();//cur--将数组最后一个元素删除,即回退一步便于递归回退 } cur_iv.pop_back();//cur--将数组最后一个元素删除,即回退一步便于递归回退 return ivv; } if(root->left!=NULL) { cur_iv.push_back(root->val); pathSum(root->left,sum-root->val); } if(root->right!=NULL) { cur_iv.push_back(root->val); pathSum(root->right,sum-root->val); } cur_iv.pop_back();//cur--将数组最后一个元素删除,即回退一步便于递归回退 return ivv; } };
方法2:利用一个栈保存当前遍历路径,一个变量保存当前栈内元素的和。(类似的题目好多都可以利用栈来保存路径,特别是要输出多个路径的情况时)------这个方法理解简单,而且速度快,22ms左右.(方法1好像是800ms左右)
/** * 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> > ivv;//保存最终结果的变量 vector<int> curStack;//用vector作栈来用,保存当前路径 int curSum=0;//用来保存当前栈内所有元素的和 pSum(root,sum,ivv,&curSum,curStack); return ivv; } private: void pSum(TreeNode *root,int sum,vector<vector<int> > &ivv,int *pCurSum,vector<int> &curStack) { if(root==NULL) return ; curStack.push_back(root->val); (*pCurSum)+=(root->val); if(root->left==NULL && root->right==NULL) { if(*pCurSum==sum)//找到一个结果 ivv.push_back(curStack); //叶子节点回退 curStack.erase(curStack.end()-1);//出栈 (*pCurSum)-=root->val;//更新和 return ; } if(root->left!=NULL) pSum(root->left,sum,ivv,pCurSum,curStack); if(root->right!=NULL) pSum(root->right,sum,ivv,pCurSum,curStack); //非叶子节点回退 curStack.erase(curStack.end()-1);//出栈 (*pCurSum)-=root->val;//更新和 return ; } };