- 利用回溯的方法去做。
- 注意是到叶子节点。
- 注意如果路径相等没必要清楚path,因为是回溯会给清除的。
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param root TreeNode类 * @param sum int整型 * @return int整型vector<vector<>> */ vector<vector<int> > pathSum(TreeNode* root, int sum) { // write code here vector<vector<int>> results; if(!root){ return results; } vector<int> path; int sum_current = 0; pre_order(root,path,results,sum_current,sum); return results; } void pre_order(TreeNode* root, vector<int>& path,vector<vector<int> >& results,int sum,int target){ if(!root){ return; } sum += root->val; path.push_back(root->val); if(!root->left&&!root->right&&sum == target){ results.push_back(path); } pre_order(root->left,path,results,sum,target); pre_order(root->right,path,results,sum,target); sum-=root->val; path.pop_back(); } };