yes karliya yeh wala question
Lowest Common Ancester
Recursive way ya iterative way?
recursive way but the code for both these question are so similar and approaches also
class Solution {
public:
vector<vector<int>> ans;
void solve(TreeNode* root, int sum, vector<int> &x,int cs){
// base case
if(!root) return;
if(!root->left and !root->right and sum == (cs+root->val)){
// I am on a leaf node
x.push_back(root->val);
ans.push_back(x);
x.pop_back();
return;
}
// recursive case
x.push_back(root->val);
solve(root->left,sum,x,cs+root->val);
solve(root->right,sum,x,cs+root->val);
x.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if(!root) return ans;
vector<int> x;
solve(root,sum,x,0);
return ans;
}
};
I’'ll check your code for that gfg problem if i will found a mistake will let you know.
Bro try to submit this solution
bool findPath(Node *root, vector<Node*> &path, int k)
{
if (root == NULL) return false;
path.push_back(root);
if (root->data == k)
return true;
if ( (root->left && findPath(root->left, path, k)) ||
(root->right && findPath(root->right, path, k)) )
return true;
// If not present in subtree rooted with root, remove root from
// path[] and return false
path.pop_back();
return false;
}
Node* lca(Node* root ,int n1 ,int n2 )
{
vector<Node*> path1, path2;
if ( !findPath(root, path1, n1) || !findPath(root, path2, n2))
return NULL;
int i;
for (i = 0; i < path1.size() && i < path2.size() ; i++)
if (path1[i] != path2[i])
break;
return path1[i-1];
}
And pop krna pdega cause without it residual elements ni niklenge. Submit this and your solution will get accepted.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
You don’t give me rating, please do.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.