Path Sum II
Description:
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] ]
Code:
1 void pathSum(TreeNode* root, int sum, vector<int>&path,vector< vector<int> >&result) 2 { 3 path.push_back(root->val); 4 if (root->left == NULL && root->right == NULL && root->val == sum) 5 result.push_back(path); 6 if (root->left!=NULL) 7 pathSum(root->left, sum-root->val, path,result); 8 if (root->right!=NULL) 9 pathSum(root->right, sum-root->val, path,result); 10 path.pop_back(); 11 } 12 vector<vector<int>> pathSum(TreeNode* root, int sum) { 13 vector< vector<int> >result; 14 if (root==NULL) 15 return result; 16 vector<int>path; 17 pathSum(root,sum,path,result); 18 return result; 19 }