/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void FindPath(TreeNode *root,int sum,int ¤tSum,vector<int> &path,vector<vector<int> >&result) { currentSum+=root->val; path.push_back(root->val); bool isLeaf=root->left==NULL && root->right==NULL; if(currentSum==sum && isLeaf) { result.push_back(path); } if(root->left!=NULL) FindPath(root->left,sum,currentSum,path,result); if(root->right!=NULL) FindPath(root->right,sum,currentSum,path,result); currentSum-=root->val; path.pop_back(); } vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int> > result; if(root==NULL) return result; vector<int> path; int currentSum=0; FindPath(root,sum,currentSum,path,result); return result; } };
113. Path Sum II
最新推荐文章于 2019-06-03 15:12:13 发布