本文介绍了二进制搜索树实现.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图实现二进制搜索树,但是我认为我的插入函数犯了一个错误.这是我的代码
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.
更多推荐
二进制搜索树实现.
发布评论