此二进制树代码出现问题(在c++中)
Troubled with this binary tree code (in c++)?
这是我为二进制树的插入和有序遍历而编写的代码。不过我现在有点乱了。你能帮我纠正一下吗?插入代码中的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 = NULL;
所以你的while循环永远不会被输入。
请注意,nroot=createnode(value);
不会将节点追加到树中。你可以使用双指针。
编辑:根据yeldar 的要求
void insert(const std::string& value) {
binarynode **node = &root;
while (*node) {
if (value >= (*node)->data) {
node=&(*node)->right;
} else {
node=&(*node)->left;
}
}
*node=createnode(value);
}
编辑:不使用双指针
void insert(const std::string& value) {
if (root == NULL) {
root = createnode(value);
return;
}
binarynode *node = root;
binarynode *parent = NULL;
while (node) {
parent = node; // we should store the parent node
node = value >= parent->data ? parent->right : parent->left;
}
if (value >= parent->data) {
parent->right = createnode(value);
} else {
parent->left = createnode(value);
}
}
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题