Problem Statement could be found @https://leetcode.com/problems/path-sum-iii/
Solution -
Idea is to save the sum of all intermediate nodes from Root Node to a given node. Try adding the value of current nodes to all the stored values and compare it with the required value. To store all required value we can use stack. Here, I'm using vector to implement Stack
Following is the code which is accepted by Leetcode. It took 138 msec to execute 126 test cases
class Solution {
int count;
int k;
public:
void trav(TreeNode *root, vector<int> s){
if (root == NULL){
return;
}
if (root->val == k){
count++;
}
vector<int> temp;
for (int i=0;i<s.size();i++){
if ((s[i] + root->val) == k){
count ++;
}
temp.push_back(s[i] + root->val);
}
temp.push_back(root->val);
trav(root->left, temp);
trav(root->right, temp);
temp.pop_back();
}
int pathSum(TreeNode* root, int sum) {
count = 0;
k = sum;
vector<int> s;
trav(root, s);
return count;
}
};
Solution -
Idea is to save the sum of all intermediate nodes from Root Node to a given node. Try adding the value of current nodes to all the stored values and compare it with the required value. To store all required value we can use stack. Here, I'm using vector to implement Stack
Following is the code which is accepted by Leetcode. It took 138 msec to execute 126 test cases
class Solution {
int count;
int k;
public:
void trav(TreeNode *root, vector<int> s){
if (root == NULL){
return;
}
if (root->val == k){
count++;
}
vector<int> temp;
for (int i=0;i<s.size();i++){
if ((s[i] + root->val) == k){
count ++;
}
temp.push_back(s[i] + root->val);
}
temp.push_back(root->val);
trav(root->left, temp);
trav(root->right, temp);
temp.pop_back();
}
int pathSum(TreeNode* root, int sum) {
count = 0;
k = sum;
vector<int> s;
trav(root, s);
return count;
}
};
No comments:
Post a Comment