这是我为二叉树的插入和中序遍历编写的代码。但是我现在有点搞砸了。你能帮我纠正这个吗?插入代码中的 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/