Home > front end >  Using recursion in C class - Passing its own data member
Using recursion in C class - Passing its own data member

Time:10-13

I am writing a pre-order traversal for Tree class:

class Tree {
public:
  ...
  void preOrder(TreeNode* root)
    {
        if (root != nullptr)
        {
            cout << root->key << " ";
            preOrder(root->left);
            preOrder(root->right);
        }
    }
  
private:
  TreeNode* root = nullptr;
}

I want to pass Tree's root data member to preOrder so that in main.cpp, I call the function like this:

Tree.preOrder();

So I code like this

void preOrder(TreeNode* root = this->root)

but compiler generate error

'this' may only be used inside a nonstatic member function

Is there anyway to fix this? Or I am going to use iterative instead of recursive traversal.

CodePudding user response:

Like the error message says, you can't use this in a method parameter. Just define a 0-parameter overload of preOrder() that calls the 1-parameter version.

class Tree {
public:
   ...

    void preOrder()
    {
        preOrder(root);
    }

    void preOrder(TreeNode* aRoot)
    {
        if (aRoot)
        {
            cout << aRoot->key << " ";
            preOrder(aRoot->left);
            preOrder(aRoot->right);
        }
    }
  
private:
  TreeNode* root = nullptr;
};
  • Related