Problem Statment:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example: Given the below binary tree and sum = 22
,
5 / 4 8 / / 11 13 4 / / 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
Solutions:
This problem is same with path sum i, in last problem we just need to verify if there exists one this kind path, however, in this problem, we need store all possible paths.
What different is the return type, actually, there is no bit difference.
Traverse version:
1 class Solution { 2 public: 3 // This is traverse version 4 void pathFind(TreeNode* node, int sum, vector<int> cur_path, vector<vector<int>>& path_set){ 5 if(node == NULL){ 6 return; 7 } 8 sum -= node->val; 9 cur_path.push_back(node->val); 10 if(sum == 0 && node->left == NULL && node->right == NULL){ 11 path_set.push_back(cur_path); 12 return; 13 } 14 if(node->left){ 15 pathFind(node->left, sum, cur_path, path_set); 16 } 17 if(node->right){ 18 pathFind(node->right, sum, cur_path, path_set); 19 } 20 return; 21 } 22 vector<vector<int>> pathSum(TreeNode* root, int sum) { 23 vector<vector<int>> path_set; 24 vector<int> cur_path; 25 pathFind(root, sum, cur_path, path_set); 26 return path_set; 27 } 28 };
Divide and conquer version:
1 class Solution { 2 public: 3 // This is divide and conquer version 4 vector<vector<int>> getPath(TreeNode* node, int sum, vector<int> path){ 5 vector<vector<int>> path_set; 6 if(node == NULL){ 7 return path_set; 8 } 9 path.push_back(node->val); 10 11 if(node->left == NULL && node->right == NULL && sum - node->val == 0){ 12 path_set.push_back(path); 13 return path_set; 14 } 15 16 vector<vector<int>> left_set = getPath(node->left, sum - node->val, path); 17 vector<vector<int>> right_set = getPath(node->right, sum - node->val, path); 18 19 path_set.insert(path_set.end(), left_set.begin(), left_set.end()); 20 path_set.insert(path_set.end(), right_set.begin(), right_set.end()); 21 return path_set; 22 } 23 24 vector<vector<int>> pathSum(TreeNode* root, int sum) { 25 vector<int> path; 26 return getPath(root, sum, path); 27 } 28 };