Skip to content

Instantly share code, notes, and snippets.

@vyruz
Created February 1, 2013 01:13
Show Gist options
  • Save vyruz/4688330 to your computer and use it in GitHub Desktop.
Save vyruz/4688330 to your computer and use it in GitHub Desktop.
#include "binary_search_tree.h"
bt_node* init_node(int data) {
// implement me
bt_node* new_node;
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
void insert_recursively(bt_node* top, bt_node* new_node){
if(new_node->data < top->data){
if(top->left == NULL){
top->left = new_node;
}else{
insert_recursively(top->left, new_node);
}
}else{
if(top->right == NULL){
top->right = new_node;
}else{
insert_recursively(top->right, new_node);
}
}
}
void insert(bt_node** top_ref, bt_node* new_node) {
// implement me
if(*top_ref == NULL){
*top_ref = new_node;
}else{
insert_recursively(*top_ref, new_node);
}
}
void insert_data(bt_node** top_ref, int data) {
// implement me
bt_node* new_node = init_node(data);
insert(top_ref, new_node);
}
void remove_recursively(bt_node* top, int data){
if(top == NULL){
return;
}
if(top->data == data){
if(top->right == NULL && top->left == NULL){
top->data = NULL;
}else if(top->right == NULL || top->left == NULL){
if(top->right == NULL){
top->data = (top->left)->data;
}else{
top->data = (top->right)->data;
}
}else{
}
}else{
if(top->data < data){
remove_recursively(top->left, data);
}else{
remove_recursively(top->right, data);
}
}
}
void remove(bt_node** top_ref, int data) {
// implement me
if(*top_ref == NULL){
return;
}else{
if((*top_ref)->data == data){
if((*top_ref)->left == NULL && (*top_ref)->right == NULL){
(*top_ref)->data = NULL;
}
}else{
remove_recursively(*top_ref, data);
}
}
}
bool contains(bt_node* top, int data) {
// implement me
if(top == NULL){
return false;
}
if(top->data == data){
return true;
}else{
if(top->data < data){
contains(top->left, data);
}else{
contains(top->right, data);
}
}
if(top->right == NULL && top->left == NULL){
return false;
}
}
bt_node* get_node(bt_node* top, int data) {
// implement me
if(top == NULL){
return NULL;
}
if(top->data == data){
return top;
}else{
if(top->data < data){
return get_node(top->left, data);
}else{
return get_node(top->right, data);
}
}
if(top->right == NULL && top->left == NULL){
return NULL;
}
}
int size(bt_node* top) {
// implement me
int count = 0;
if(top == NULL){
return count;
}else{
if(top->right == NULL && top->left == NULL){
return count + 1;
}else{
if(top->right == NULL || top->left == NULL){
count++;
if(top->right == NULL){
count = count + size(top->left);
}else{
count = count + size(top->right);
}
}else{
count = count + 2;
count = count + size(top->right);
count = count + size(top->left);
}
}
}
}
void to_array(bt_node* top, int arr[]) {
// implement me
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment