C++ 树无法插入值

标签 c++ tree

这段代码是我写的。但它不插入和打印值。谁能检查并告诉问题?

struct Node{

    int value;
    Node* left;
    Node* right;
};

class Tree {

Node* root;

public:
Tree insertNode( Node* tree,int val)
{
    if(tree==NULL)
    {
    tree = new Node;
    tree->value=val;
    tree->left=NULL;
    tree->right=NULL;

    }
    else if (val<=tree->value){ 
    insertNode(tree->left,val);
    }
    else
    {
        insertNode(tree->right,val);
    }

    return *this;
}


insert(int val)
{
    insertNode(root, val);

}

void printTree(Node* root)
{


    if(!root)
    {
        cout<<"Tree is empty"<<endl;
        return;
    }

    printTree(root->left);
    cout<<root->value;
    printTree(root->right);


}


print()
{
    printTree(this->root);
}


};



int main(){


Tree* Nodd = new Tree();
Nodd->insert(12);
Nodd->insert(10);
Nodd->print();


}

当我运行这个程序时,只需在 insertNode 函数的第一个 if 语句中运行。我想,我错过了什么,做错了什么。

最佳答案

Tree insertNode( Node* tree,int val) 在此函数中,您应该通过引用传递节点指针以便能够修改节点,因此正确的参数是
树 insertNode( Node* &tree,int val)

关于C++ 树无法插入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40292655/

相关文章:

java - 寻找集合的幂集

c++ - OpenCV 3.0 主动轮廓(蛇形)算法

c++ - 在 C++ 和优化中缺少返回值的不稳定行为

algorithm - 寻找树的中心

python - 将 python NLTK 解析树保存到图像文件

c++ - 谁是 std::future 的创建者?

c++ - 在文本框上正确呈现 unicode 字符

css - 设置单个 Vaadin 树元素的样式

javascript - csv数据到d3中的嵌套json树

python - 我应该使用哪些模块来创建游戏树?