C++ 创建空二叉树函数

C++ 创建空二叉树函数,c++,binary-tree,C++,Binary Tree,我现在正在创建一个二叉树程序,到目前为止,我已经实现了很多函数。我现在想添加一个函数来创建一个空树,但我还没有弄清楚如何做到这一点 作为我的示例,下面是我创建树的代码,其中包含要存储的初始值: BST::BST() { root = nullptr; } void BST::createWithRoot(int key) { createWithRootPrivate(key, root); } void BST::createWithRootPrivate(int key,

我现在正在创建一个二叉树程序,到目前为止,我已经实现了很多函数。我现在想添加一个函数来创建一个空树,但我还没有弄清楚如何做到这一点

作为我的示例,下面是我创建树的代码,其中包含要存储的初始值:

BST::BST() {
    root = nullptr;
}

void BST::createWithRoot(int key) {
    createWithRootPrivate(key, root);
}

void BST::createWithRootPrivate(int key, node* Ptr) {
    if (root == nullptr) {
        root = createLeaf(key);
    }   
}

BST::node* BST::createLeaf(int key) {
    node* n = new node;
    n -> key = key;
    n -> left = nullptr;
    n -> right = nullptr;

    return n;
}
我曾尝试过做类似的事情,但毫不奇怪没有成功:

BST::node* BST::createLeaf(int key) {
    node* n = new node;
    n -> key = nullptr;
    n -> left = nullptr;
    n -> right = nullptr;

    return n;
}

有人有什么建议吗?我确信它很简单,但是对于C++和二进制树来说,我是很新的。

你必须简单地添加一个空构造函数方法,比如这个< /p>
BST::BST(){
    root = nullptr;// as says Klamer
}

你说它不起作用是什么意思?您得到了什么错误?node*n=新节点;n->key=nullptr;n->left=nullptr;n->right=nullptr;-首先为更干净的代码创建BST::node的默认构造函数。我将使用root==nullptr来指示空树。所以创建它只会返回nullptr…@KlamerSchutte谢谢。这似乎是我一直在寻找的解决方案。我已经用一些代码编辑了我的问题,实际上我已经有了。。。不确定它是否做同样的事情。