Translate

Saturday, 30 August 2014

Binary Search Trees

A binary tree is made of nodes, where each node contains a "left" pointer, a "right" pointer, and a data element. The "root" pointer points to the topmost node in the tree. The left and right pointers recursively point to smaller "subtrees" on either side. A null pointer represents a binary tree with no elements -- the empty tree. The formal recursive definition is: a binary tree is either empty (represented by a null pointer), or is made of a single node, where the left and right pointers (recursive definition ahead) each point to a binary tree.



Operations on a BST
  • Add a new value
  • Search for a value
  • Remove a value
  • Get values from BST in order
Here is a sample of Binary Search Tree Algorithm:

Destroy Tree

void destroy_tree(struct node* leaf){
     if(leaf != 0){
             destroy_tree(leaf->left);
             destroy_tree(leaf->right);
             free(leaf);
     }
}

Insert Node

void insert_node(int key, struct node **leaf){
     if(*leaf == NULL){
              *leaf = (struct node*) malloc(sizeof(struct node));
              (*leaf)->key_value = key;
              (*leaf)->left = 0;
              (*leaf)->right = 0;
     }else if(key < (*leaf)->key_value){

           insert_node(key, &(*leaf)->left);
     }else if(key > (*leaf)->key_value){

           insert_node(key, &(*leaf)->right);
     }
}

Search Tree

struct node* search_tree(int key, struct node *leaf){
       if(leaf != NULL){
               if(key==leaf->key_value){
                     return leaf;
               }else if(key<leaf->key_value){

                     return search_tree(key, leaf->left);
               }else{

                     return search_tree(key, leaf->right);
               }
       }
}

Tree Depth

int tree_depth(struct node* ptr){
    int ldepth,rdepth;
    if(ptr==NULL){
        return 0;
    }else{
          ldepth = tree_depth(ptr->left);
          rdepth = tree_depth(ptr->right);
          if(ldepth>rdepth){
                   return ldepth + 1;
          }else{
                return rdepth + 1;
          }
    }
}


No comments:

Post a Comment