二进制搜索树实现.

编程入门 行业动态 更新时间:2024-10-24 10:20:42
本文介绍了二进制搜索树实现.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图实现二进制搜索树,但是我认为我的插入函数犯了一个错误.这是我的代码

I was trying to implement binary search tree but I think I have made a mistake in my insert function. Here's my code

#include<iostream> #include<memory.h> #include <cstddef> using namespace std; struct bst_node { int info; struct bst_node *left_node_ptr; struct bst_node *right_node_ptr; }; struct bst_node* getnode(int x) { struct bst_node* ret= new bst_node; ret->info=x; ret->left_node_ptr=NULL; ret->right_node_ptr=NULL; return ret; } void insert(struct bst_node **root, int var_info) { struct bst_node *temp=(*root); // Links the temporary pointer to root of the BST while(temp!=NULL) // Loop till I find a suitable position for inserting { if(temp->info > var_info) { temp=temp->left_node_ptr; } else { temp=temp->right_node_ptr; } } temp= getnode(var_info); return ; } /* Recursive In order Traversal */ void inorder_recursive( struct bst_node * L) { if(L!= NULL) { inorder_recursive(L->left_node_ptr); cout<<L->info<<endl; inorder_recursive(L->right_node_ptr); } return; } int main() { struct bst_node* my_root= getnode(5); insert(&my_root, 6); insert(&my_root, 3); /* int x=1; int arr[]= {}; while(x) { cin>>x; insert(&my_root, x); }*/ inorder_recursive(my_root); return 0; }

推荐答案

您从未真正设置节点的left_node_ptr或right_node_ptr值.您的插入函数在树上运行,找到放置新节点的正确位置,然后分配该节点-但实际上并没有将新节点附加到找到的父节点的左侧或右侧.

You never actually set the left_node_ptr or right_node_ptr values of your nodes. Your insert function runs down the tree finding the correct place to put the new node, then allocates the node - but doesn't actually attach the new node to the left or right of the parent you found.

更多推荐

二进制搜索树实现.

本文发布于:2023-11-29 08:22:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645855.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!