【发布时间】:2017-04-16 23:07:02
【问题描述】:
所以我为在 BST(二叉搜索树)中插入节点编写了这段代码,但程序总是打印出树是空的。我想我所做的函数调用有问题。你能解释一下这个问题吗?
#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;
}
【问题讨论】:
-
node* root;中有一个未初始化的指针。除非您为其分配该值,否则它不会设置为 NULL。 -
我将其更改为 NULL。还有一个问题是输出总是:“树是空的,”
-
下一个问题是将
node指针按值传递给insert。这意味着对指针的任何更改都是该函数的本地更改,并且不会影响main中的指针。
标签: c++ binary-tree binary-search-tree