3
0
mirror of https://github.com/CrazyRedMachine/popnhax.git synced 2025-02-17 10:48:31 +01:00
popnhax/util/bst.cc

45 lines
1.2 KiB
C++
Raw Normal View History

2024-05-20 21:54:49 +02:00
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "bst.h"
bst_t* bst_search(bst_t *root, uint32_t val)
{
if( root == NULL || root->data == val )
return root;
else if( val > (root->data) )
return bst_search(root->right, val);
else
return bst_search(root->left,val);
}
2024-06-16 20:44:13 +02:00
bst_t* bst_insert_ex(bst_t *root, uint32_t val, void* extra_data, void*(*extra_data_cb)(void *arg1, void *arg2))
2024-05-20 21:54:49 +02:00
{
if ( root == NULL )
{
bst_t *p;
p = (bst_t *)malloc(sizeof(bst_t));
p->data = val;
p->left = NULL;
p->right = NULL;
2024-06-16 20:44:13 +02:00
p->extra_data = extra_data;
2024-05-20 21:54:49 +02:00
return p;
}
2024-06-16 20:44:13 +02:00
else if ( extra_data != NULL && extra_data_cb != NULL && val == root->data )
{
//already existing, process extra_data
root->extra_data = extra_data_cb(root->extra_data, extra_data);
}
2024-05-20 21:54:49 +02:00
else if ( val > root->data )
2024-06-16 20:44:13 +02:00
root->right = bst_insert_ex(root->right, val, extra_data, extra_data_cb);
2024-05-20 21:54:49 +02:00
else
2024-06-16 20:44:13 +02:00
root->left = bst_insert_ex(root->left, val, extra_data, extra_data_cb);
2024-05-20 21:54:49 +02:00
return root;
2024-06-16 20:44:13 +02:00
}
bst_t* bst_insert(bst_t *root, uint32_t val)
{
return bst_insert_ex(root, val, NULL, NULL);
2024-05-20 21:54:49 +02:00
}