两次AC,第一次错误在于没有考虑可能会有负数结点的出现。
/** * 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 find(TreeNode* root, int sum,int target,vector<int>& temp,vector<vector<int>>& result) { if(sum==target&&root->left==NULL&&root->right==NULL) result.push_back(temp); else { if(root==NULL) return; else { if(root->left!=NULL) { temp.push_back(root->left->val); find(root->left,sum+(root->left->val),target,temp,result); temp.pop_back(); } if(root->right!=NULL) { temp.push_back(root->right->val); find(root->right,sum+(root->right->val),target,temp,result); temp.pop_back(); } } } return; } vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> result; if(root==NULL) return result; else { vector<int> temp; temp.push_back(root->val); find(root,root->val,sum,temp,result); return result; } } };