BINARY SEARCH TREE

BINARY SEARCH TREE




SEARCHING

Always starts from the root, compare the data stored with the key we are searching for. If the data is less than the key value, search in the left subtree otherwise search in the right subtree.a binary search tree can reduce the search time to O(n).

Algorithm


If root.data is equal to search.data
   return root
else
   while data not found

      If data is greater than node.data
         goto right subtree
      else
         goto left subtree
         
      If data found
         return node
   endwhile 
   
   return data not found
   
end if      

INSERTION

Start from the root and go down searching for a proper location. If the data is less than the key search for empty location in the left subtree, otherwise searh for empty location in the right subtree. Insert the data if the data that want to be insert is not in the tree (NULL), won't insert duplicates.

Algorithm

If root is NULL 
   then create root node
return

If root exists then
   compare the data with node.data
   
   while until insertion position is located

      If data is greater than node.data
         goto right subtree
      else
         goto left subtree

   endwhile 
   
   insert data
 
end If  

DELETION

Deleted node is replaced by bottom most and rightmost node. There is no order among elements, so replace it with last element. If the node has only one child the way to delete is the same with linked list.
A node to be deleted :
  • is not in a tree
  • is a leaf
  • has only one child
  • has two children

Algorithm
  1. Starting from the root, find the deepest node in binary tree and the node that we want to delete.
  2. Replace the deepest node with node to be deleted.
  3. Then delete the deepest node.





Comments

Popular posts from this blog

Hash Table and Binary Tree

RANGKUMAN