Skip to content

Instantly share code, notes, and snippets.

@jitsceait
Last active August 29, 2015 14:00
Show Gist options
  • Save jitsceait/fbaed8d96517307b1a2e to your computer and use it in GitHub Desktop.
Save jitsceait/fbaed8d96517307b1a2e to your computer and use it in GitHub Desktop.
Program to prune binary search tree
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
struct node{
int value;
struct node *left;
struct node *right;
};
typedef struct node Node;
Node * prune_nodes(Node * root, int min, int max){
if(root == NULL) return NULL;
Node * root->left = prune_node(root->left, min, max);
Node * root->right = prune_node(root->right, min, max);
if(root->value < min)
Node * right_tree = root->right;
free(root);
return right_tree;
}
if (root->value > max){
Node *left_tree = root->left;
free(root);
return left_tree;
}
return root;
}
Node * create_node(int value){
Node * temp = (Node *)malloc(sizeof(Node));
temp->value = value;
temp->right= NULL;
temp->left = NULL;
}
Node * addNode(Node *node, int value){
if(node == NULL){
return create_node(value);
}
else{
if (node->value > value){
node->left = addNode(node->left, value);
}
else{
node->right = addNode(node->right, value);
}
}
return node;
}
/* Driver program for the function written above */
int main(){
Node *root = NULL;
Node * last = NULL;
Node *ptrToHead = NULL;
//Creating a binary tree
root = addNode(root,30);
root = addNode(root,20);
root = addNode(root,15);
root = addNode(root,25);
root = addNode(root,40);
root = addNode(root,37);
root = addNode(root,45);
prune_nodes(root, 22,40);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment