Why do I need this *& reference - c++


  • 0
    G

    So I've got this code, which only works when I'm passing my node as reference, anyone care to explain me why please.

    void getLeaves(vector<int> &vec, TreeNode *&n){
            
            if(n && !n->left && !n->right){
                vec.push_back(n->val);
                n = NULL;
            }
            if(n){ 
                getLeaves(vec, n->left);
                getLeaves(vec, n->right);
            }
            
        }
    
        vector<vector<int>> findLeaves(TreeNode* root) {
            
            vector<vector<int>> ans;
            vector<int> vec;
            
            while(root){
                
                vector<int> vec;
                getLeaves(vec, root);
                ans.push_back(vec);
            }
            
            return ans;
        } ```

  • 0
    G

    *& this is reference of pointer, if you don't use pointer reference, you getLeaves method just operate the copy of pointer.


  • 0
    G

    @Garlicala isn't it enough with the copy of the pointer?


  • 0
    G

    @gustavo3 if you just pass copy of pointer, the pointer will only be changed in Method: getLeaves scope. therefore, you need pass reference, the pointer will be changed deeply.


  • 0
    L

    It seems there is memory leak in the code, because there is no "delete n" before "n = NULL". But adding "delete n" before "n = NULL" will cause the code not to pass the case "[ ]".

    Don't know why.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.