I tried this question using queue
Is this approach also right for this question ?
I tried this question using queue
Is this approach also right for this question ?
yes, it seems right, you can also do this
void flatten(TreeNode* &root) {
if(root == nullptr) return;
stack<TreeNode*>q;
q.push(root);
while(!q.empty()){
TreeNode* curr = q.top();
q.pop();
if(curr->right){
q.push(curr->right);
}
if(curr->left){
q.push(curr->left);
}
if(!q.empty()){
curr->right = q.top();
}
curr->left = nullptr;
}
return;
}
this is for bfs approach.
ooh yes yes, but these approaches require a extra space for the logic, while bhaiya’s approach just plays with pointers so i guess thats better.
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.