在 C++ 中使用递归 class - 传递自己的数据成员

Using recursion in C++ class - Passing its own data member

我正在为 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;
}

我想将 Treeroot 数据成员传递给 preOrder 以便在main.cpp,我这样调用函数:

Tree.preOrder();

所以我这样编码

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

但编译器生成错误

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

有办法解决这个问题吗?或者我将使用迭代而不是递归遍历。

如错误消息所述,您不能在方法参数中使用 this。只需定义调用 1 参数版本的 preOrder() 的 0 参数重载。

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;
};