jeudi 27 février 2020

How do I pass a Self referential Structure by Reference in C++

I have the following c++ structure

struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  };

I have a function which sets TreeNode's children to null if their subtrees do not contain the value 1.

bool modify(TreeNode *root)
{
   if(root==NULL)
   return false;

   if(root->val!=1)
   {
      bool l = modify(root->left);
      bool r = modify(root->right);
      if(l||r)
      {
       return true;
      }
      else
      {
       root = NULL;
       return false;
      }
   }
   else
   return true; 
}

How do I pass TreeNode *root by reference so that modifications made inside modify() are persisted?

Aucun commentaire:

Enregistrer un commentaire