The following code is the function to "Delete Leaves With a Given Value(target)". Although I get what the code is doing, suppose I reach a leaf with target value and do root=NULL
. Then, as it is passed by reference, won't all the roots it would return to become NULL
? Like when we pass an int by reference, e.g., count and increment it, its value gets updated and remains the same even when the function returns to where it was called. So, why, in the below code, root
's value does not change?
void helper(TreeNode* &root,int target){
if(!root)return;
helper(root->left,target);
helper(root->right,target);
if(root->val==target and root->left == NULL and root->right==NULL){
root=NULL;
}
return;
}