C++ 二进制搜索树的输出不正确
我已经调试了代码,没有发现任何错误。下面的代码并没有打印二进制搜索树(BST)的所有数据。只有根节点和最后两个节点按顺序遍历显示C++ 二进制搜索树的输出不正确,c++,tree,binary-search-tree,C++,Tree,Binary Search Tree,我已经调试了代码,没有发现任何错误。下面的代码并没有打印二进制搜索树(BST)的所有数据。只有根节点和最后两个节点按顺序遍历显示 struct node{ int key; node *left; node *right; }; node* newNode(int data){ node *ptr=new node; ptr->key=data; ptr->left=ptr->right=NULL; return pt
struct node{
int key;
node *left;
node *right;
};
node* newNode(int data){
node *ptr=new node;
ptr->key=data;
ptr->left=ptr->right=NULL;
return ptr;
}
node* insert_node(node* root,int data){
if(root==NULL){
root=newNode(data);
}else if(data<=root->key){
root->left=newNode(data);
}else{
root->right=newNode(data);
}
return root;
}
void inorder(node* root){
if(root==NULL)
return;
inorder(root->left);
cout<<root->key<<" ";
inorder(root->right);
}
int main(){
node *root=NULL;
root=insert_node(root,10);
root=insert_node(root,12);
root=insert_node(root,15);
root=insert_node(root,1);
root=insert_node(root,20);
inorder(root);
return 0;
}
struct节点{
int键;
节点*左;
节点*右;
};
node*newNode(int数据){
node*ptr=新节点;
ptr->key=数据;
ptr->left=ptr->right=NULL;
返回ptr;
}
节点*插入\节点(节点*根,整数数据){
if(root==NULL){
root=newNode(数据);
}else if(数据键){
根->左=新节点(数据);
}否则{
root->right=newNode(数据);
}
返回根;
}
无效索引(节点*根){
if(root==NULL)
返回;
顺序(根->左);
cout插入函数没有任何递归或迭代实现来查找叶节点。因此,新节点将替换根节点的子节点。我认为这在注释部分中得到了很好的强调
下面是一段代码,其中使用迭代定位叶节点,然后插入新节点
node *insert_node( node *root, int data){
struct node *ptr, *nodeptr, *parentptr;
ptr = (struct node*)malloc(sizeof(struct node));
ptr->data = data;
ptr->left = NULL;
ptr->right = NULL;
if(root==NULL) //tree is empty
{
root=ptr;
root->left=NULL;
root->right=NULL;
}
else
{
parentptr=NULL; // keep the address of parent node
nodeptr=root;
while(nodeptr!=NULL)
{
parentptr=nodeptr;
if(data<nodeptr->data)
nodeptr=nodeptr->left;
else
nodeptr = nodeptr->right;
}
// now the parentptr contains address of the leaf node
if(data<parentptr->data)
parentptr->left = ptr;
else
parentptr->right = ptr;
}
return root;
}
node*插入节点(node*根,int数据){
结构节点*ptr,*nodeptr,*parentptr;
ptr=(结构节点*)malloc(sizeof(结构节点));
ptr->data=数据;
ptr->left=NULL;
ptr->right=NULL;
如果(root==NULL)//树为空
{
根=ptr;
根->左=空;
root->right=NULL;
}
其他的
{
parentptr=NULL;//保留父节点的地址
nodeptr=根;
while(nodeptr!=NULL)
{
parentptr=nodeptr;
如果(数据)
nodeptr=nodeptr->left;
其他的
nodeptr=nodeptr->right;
}
//现在,parentptr包含叶节点的地址
如果(数据)
parentptr->left=ptr;
其他的
parentptr->right=ptr;
}
返回根;
}
您还可以参考其他一些源来递归实现相同的功能。假设您首先插入一个data=10
的节点(该节点将充当根节点)。然后插入一个具有data=8
的节点,使其插入到左侧、右侧?好的,现在插入一个具有data=6
的节点。根节点保持不变,因此如果我没有弄错的话,具有data=6
的节点将覆盖具有data=8
的节点。此外,这会造成内存泄漏,因为具有的节点>data=8
没有被删除并且变得不可访问我已经调试了代码并且没有发现任何错误——如果没有发现错误,为什么会有问题?如果您知道某些东西不能正常工作,那么您就有一个错误。@Fureeish数据只在leaf-through递归中添加。当插入data=8
时,它将l将被插入到根目录的左侧,但当data=6
将被插入时,它将被插入到data=8
节点的左侧。@PaulMcKenzie我的意思是我用钢笔调试,没有发现错误。没有。我只是测试了你的代码,它不正确。如果你调用root=insert\u节点(根目录,10)
后跟root=insert_node(root,8);
和root=insert_node(root,6);
,std::cout left->键;
将显示6
,这不是您所期望的-您所期望的8