[LeetCode] Path Sum II
Well, a typical backtracking problem. The code is as follows. You may walk through it using the example in the problem statement to see how it works.
1 class Solution { 2 public: 3 vector<vector<int>> pathSum(TreeNode* root, int sum) { 4 vector<vector<int> > paths; 5 vector<int> path; 6 findPaths(root, sum, path, paths); 7 return paths; 8 } 9 private: 10 void findPaths(TreeNode* node, int sum, vector<int>& path, vector<vector<int> >& paths) { 11 if (!node) return; 12 path.push_back(node -> val); 13 if (!(node -> left) && !(node -> right) && sum == node -> val) 14 paths.push_back(path); 15 findPaths(node -> left, sum - node -> val, path, paths); 16 findPaths(node -> right, sum - node -> val, path, paths); 17 path.pop_back(); 18 } 19 };