简体   繁体   中英

Binary tree nodes with index

I need to make optimized search for vector using binary search tree. for example I have vector<int> numbers where I store {5,4,3,2,1} then I copy those 1,2,3,4,5 to binary tree and need to return index where it is stored in vector. For example, search(4) will have to return 1 because numbers[1] = 4 I've tried giving nodes index but they don't match in the end Is there a better solution or how do I correctly give index to tree nodes

struct node {
    int data;
    int index;
    node* left;
    node* right;
};
    node* insert(int x, node* t) {
    if(t == NULL) {
        t = new node;
        t->data = x;
        t->index = 0;
        t->left = t->right = NULL;
    }
    else if(x < t->data) {
        t->left = insert(x, t->left);
        t->index += 1;
    }

    else if(x > t->data) {
        t->right = insert(x, t->right);
        t->index += 0;
    }
    return t;
}

node* find(node* t, int x)  {
    if(t == NULL)
        return NULL;
    else if(x < t->data) {
        return find(t->left, x);
    }
    else if(x > t->data) {
        return find(t->right, x);
    }

    else
        return t;
}

int main() {
    BST t;
    vector<int> storage;
    for ( int i =0; i< 10; i++) {
        storage.push_back(rand()%100 +1);
        t.insert(storage[i]);
    }
    t.display();
    t.search(15);
}
    node* insert(int x, node* t, int index)
{
    if(t == NULL)
    {
        t = new node;
        t->data = x;
        t->index = index;
        t->left = t->right = NULL;
    }
    else if(x < t->data)
    {
        t->left = insert(x, t->left, index);

    }

    else if(x > t->data)
    {
        t->right = insert(x, t->right, index);

    }

    return t;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM