C++ 什么';BST插入的代码有什么问题?
因此,我编写了这段代码,用于在BST(二进制搜索树)中插入节点,但程序总是打印树为空。我想我所做的函数调用有问题。你能解释一下这个问题吗C++ 什么';BST插入的代码有什么问题?,c++,binary-tree,binary-search-tree,C++,Binary Tree,Binary Search Tree,因此,我编写了这段代码,用于在BST(二进制搜索树)中插入节点,但程序总是打印树为空。我想我所做的函数调用有问题。你能解释一下这个问题吗 #include <bits/stdc++.h> #include <conio.h> using namespace std; struct node { int key; node* left; node* right; };
#include <bits/stdc++.h>
#include <conio.h>
using namespace std;
struct node
{
int key;
node* left;
node* right;
};
void insert(node* root, int item)
{
if(root == NULL)
{
node* temp = new node();
temp->key = item;
temp->left = NULL;
temp->right = NULL;
root = temp;
}
else
{
if((root->key)>item)
{
insert(root->left,item);
}
else
{
insert(root->right,item);
}
}
}
void inorder(node* root)
{
if(root!=NULL)
{
inorder(root->left);
cout<<" "<<root->key<<" ";
inorder(root->right);
}
else cout<<"The tree is empty.";
}
int main()
{
// cout<<endl<<" Here 5 ";
node* root = NULL;
int flag = 1 , item;
while(flag == 1)
{
cout<<"Enter the number you want to enter : ";
cin>>item;
// cout<<endl<<" Here 6";
insert(root, item);
cout<<"Do you want to enter another number (1 -> YES)?";
cin>>flag;
}
cout<<"The final tree is :";
inorder(root);
getch();
return 0;
}
#包括
#包括
使用名称空间std;
结构节点
{
int键;
节点*左;
节点*右;
};
无效插入(节点*根,int项)
{
if(root==NULL)
{
node*temp=新节点();
temp->key=项目;
temp->left=NULL;
temp->right=NULL;
根=温度;
}
其他的
{
如果((根->键)>项)
{
插入(根->左,项目);
}
其他的
{
插入(根->右侧,项目);
}
}
}
无效索引(节点*根)
{
if(root!=NULL)
{
顺序(根->左);
cout首先,插入有点不正确。必须通过引用传递根指针。例如:
void insert(node *& root, int item)
{
if(root == NULL)
{
node* temp = new node();
temp->key = item;
temp->left = NULL;
temp->right = NULL;
root = temp;
}
else
{
if ((root->key) > item)
{
insert(root->left,item);
}
else
{
insert(root->right,item);
}
}
}
在结构上与代码相同(除了对根的引用)
此外,您的索引遍历非常奇怪,因为它会打印出消息“树为空”。每次遍历检测到空节点时,我都会这样修改:
void inorder(node* root)
{
if (root == NULL)
return;
inorder(root->left);
cout<<" "<<root->key<<" ";
inorder(root->right);
}
您在节点*root;
中有一个未初始化的指针。除非您为其分配该值,否则它不会设置为NULL。我将其更改为NULL。但仍然存在一个问题,即输出总是:“树为空,”下一个问题是将节点
指针按值传递到insert
。这意味着对指针的任何更改都是该函数的本地更改,不会影响main
中的指针。
int main()
{
node* root = NULL;
int flag = 1 , item;
while(flag == 1)
{
cout<<"Enter the number you want to enter : ";
cin>>item;
insert(root, item);
cout<<"Do you want to enter another number (1 -> YES)?";
cin>>flag;
}
cout<<"The final tree is :";
if (root == NULL)
cout << "The tree is empty.";
else
inorder(root);
cout << endl;
return 0;
}