c++ - 二叉搜索树实现。

标签 c++ binary-search-tree

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

#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_ptrright_node_ptr 值。您的插入函数沿着树向下运行,找到放置新节点的正确位置,然后分配节点 - 但实际上并没有将新节点附加到您找到的父节点的左侧或右侧。

关于c++ - 二叉搜索树实现。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5498487/

相关文章:

c++ - 如何测试预处理器符号是否是#define'd但没有值(value)?

c++ - 使用指向数组的指针进行合并排序

java - 使用Java从最大数到最小数打印二叉搜索树

java - 打印二叉树中所有大于或等于传入方法的值的方法

c - 是否有充分的理由不在一个节点中包含多个节点指针以在多个数据结构中使用?

c++ - 参数中的星号和与号

c++ - XCode5 使用 iPhone 进行开发

ocaml - 如何在 OCaml 中编写 BST 的迭代中序遍历

java - 如何递归地将列表转换为 BSTree?

c++ - ESP8266:如何在station模式下获取客户端的MAC地址(STA_MODE)?