//深度优先遍历,或者说先根遍历。保存路径上的点,到达叶子结点时,判断和是不是sum.
/** * 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<int> cur; int curSum = 0; vector<vector<int>> ans; dfs(root, sum, curSum, cur, ans); return ans; } void dfs(TreeNode *root, int sum, int curSum, vector<int> &cur, vector<vector<int>> &ans){ if(root == nullptr) { return; } cur.push_back(root->val); //预先计算好了sum if(sum == curSum+root->val && root->left == nullptr && root->right==nullptr){ ans.push_back(cur); cur.pop_back(); return; } dfs(root->left, sum, curSum + root->val, cur, ans); dfs(root->right, sum, curSum + root->val, cur, ans); cur.pop_back(); } };