0

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;
    }
codeling
  • 11,056
  • 4
  • 42
  • 71
  • Yes, exactly as you wrote. But first you have 2 recursive calls to traverse left and right branches, and `root=NULL` is invoked only on the leaves. – pptaszni Apr 08 '22 at 08:55
  • Just removed [tag:c] from tags. Receiving by reference(`&`) is not yet supported in `C`. Although, `helper (TreeNode* &node, int target) {...}` seems more apt in this case. – जलजनक Apr 08 '22 at 09:09
  • @pptaszni leaves plus the nodes whose leaves were equal to the target and have been converted to NULL are also being deleted. – Sneha Sharma Apr 08 '22 at 09:15
  • Please show a [mre] and show where you expect `root` to become null and how you know it isn't – Alan Birtles Apr 08 '22 at 09:15
  • @AlanBirtles sorry for not being clear. The question is https://leetcode.com/problems/delete-leaves-with-a-given-value/ and the example is in the page itself. Thanks – Sneha Sharma Apr 08 '22 at 09:17
  • Please add the [mre] to the question, not in the comments and make sure it doesn't rely on external links which can die and make your question meaningless – Alan Birtles Apr 08 '22 at 09:21
  • `root` is a reference to a different pointer in every function call. – molbdnilo Apr 08 '22 at 09:23
  • @molbdnilo yes of course, got it, thanks a million! – Sneha Sharma Apr 08 '22 at 09:29
  • side note: for "modern" c++, use `nullptr` instead of `NULL` – codeling Apr 08 '22 at 09:43
  • @codeling will remember. is there a reason btw? thanks – Sneha Sharma Apr 08 '22 at 09:54
  • @SnehaSharma `nullptr` is a new keyword explicitly for the purpose of an "empty" pointer. see e.g. [NULL vs nullptr](https://stackoverflow.com/questions/20509734/null-vs-nullptr-why-was-it-replaced) here on SO for more details. – codeling Apr 08 '22 at 10:05

0 Answers0