Binary search Tree Implementation.

2019-09-05 06:43发布

问题:

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;
}

回答1:

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.



回答2:

your search goes 1 level too far. You threw away the node to which you want to attach your new child. Also temp = ... will not attach anything to your tree. You should do a while until you find the child node you want to attach to and then do either :

temp->left_node_ptr = getnode(var_info); or temp->right_node_ptr = getnode(var_info);

   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);