c++ - 对这个二叉树代码(在 C++ 中)感到困扰?

标签 c++ binary-tree

这是我为二叉树的插入和中序遍历编写的代码。但是我现在有点搞砸了。你能帮我纠正这个吗?插入代码中的 while 循环没有让任何东西进入其中。感谢您的帮助。

#include<iostream>
#include<string>
using namespace std;

class binarynode
{public:
string data;
binarynode *left;
binarynode *right;  
};

class tree
{
binarynode *root;
public:
    tree()
    {
        root=new binarynode;
        root=NULL;
    }
    binarynode* createnode(string value)
    {
        binarynode * temp;
        temp=new binarynode;
        temp->data=value;   
        temp->left=NULL;
        temp->right=NULL;
        return temp;
    }
    void insert(string value)
    {//cout<<"entered 1"<<endl;
        binarynode * nroot;
        nroot=root;

        while(nroot!=NULL)
        {//cout<<"here 2"<<endl;
        if(value> nroot->data )
        {
        //  cout<<"here 3"<<endl;
            nroot=nroot->right;
        }
        else
        if(value<nroot->data)
        {//cout<<"here 4"<<endl;
            nroot=nroot->left;
        }
        }
        nroot=createnode(value);
    }
    void inorder()
    {
        binarynode *nroot;
        nroot=root;
        printinorder(nroot);
    }
    void printinorder(binarynode * nroot)
    {
    //cout<<"entered 5"<<endl;
        if(nroot->left==NULL&&nroot->right==NULL)
        {
            cout<<nroot->data<<" ";
        }
            printinorder(nroot->left);
    cout<<nroot->data<<" ";
    printinorder(nroot->right);
    }
};

int main()
{
    tree a;
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        string value;
        cin>>value;
        a.insert(value);
    }
    a.inorder();
}

最佳答案

您在构造函数中将 NULL 分配给 root:

root = NULL;

因此您的 while 循环将永远不会进入。

关于c++ - 对这个二叉树代码(在 C++ 中)感到困扰?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30966209/

相关文章:

c++ - 在框架中使用 OpenGL 上下文编写简单的 wxWidgets 应用程序

c++ - 为什么人们在 C++ 中使用枚举作为常量,而他们可以使用 const?

c++ - 正在运行的线程中是否可以使用 QThread::quit

用于流式压缩算法的 C++ 快速位数组类

java - 二进制搜索树的深度,但有所不同

Java:二叉树递归方法

algorithm - 对二叉树中的元素进行排序

c++ - 多处理器 boost::线程?在一个处理器上运行的所有线程

c - 我想将数据插入二叉树,但在 3 个输入后显示段错误

c++ - 我的基于树的 C++ 表达式求解器存在数字被覆盖的奇怪问题?