İkili arama ağacı uygulanması.

oy
0

Ben ikili arama ağacı uygulamak için çalışıyordu ama benim insert işlevinde bir hata yapmış düşünüyorum. İşte benim kod

#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;
}
Oluştur 31/03/2011 saat 11:33
kaynak kullanıcı
Diğer dillerde...                            


2 cevaplar

oy
2

Aslında atmadı left_node_ptrya right_node_ptrda düğüm değerlerini. Kişisel insert işlevi, daha sonra yeni bir düğüm koymak için doğru yer bulmak ağacının dibine çalışır düğümü ayırır - ama aslında bulundu ebeveynin sağına veya soluna yeni bir düğüm eklemez.

Cevap 31/03/2011 saat 11:39
kaynak kullanıcı

oy
1

Arama çok uzakta 1 seviyesine gider. Sen hangi yeni çocuk eklemek istediğiniz düğümü attı. Ayrıca geçici = ... senin ağacının herhangi bir şey eklemek olmayacaktır. Eğer birini yapın sonra eklemek ve istediğiniz alt düğümü bulana kadar bir süre yapmalıdır:

TEMP> left_node_ptr = getnode (var_info); veya 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);
Cevap 31/03/2011 saat 11:39
kaynak kullanıcı

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more