Wednesday, December 3, 2014

How to check if a tree is a BST

Hello Folks,  In my previous post i have mentioned the ways to create , delete and display a binary search tree . Now let us create logic for finding out if the binary tree is a binary search tree or not !

In a binary search tree each  node and its child nodes must follow these rules.

  •  Parent node must be greater than left child node.
  •  Right child node must be greater than the parent node.
So we shall try to check if the tree satisfies above two rules by recursively traversing down the tree in both the directions  ( left branch & Right branch).


int

check_if_bst_or_not(struct binary_tree *temp)
{
  if(temp != NULL)
  {

    if(temp->pleft &&  temp->pleft->data > temp->data)
     return -1 ;
    if(temp->pright &&  temp->pright->data < temp->data)
     return -1 ;

    check_if_bst_or_not(temp->pleft);
    check_if_bst_or_not(temp->pright);

  }

 return 0;

}

In first if condition , i have tried to check if a left node exists and if it greater than the parent node , as per Rule 1 it should not be true.

In second if condition , i have tried to check if a right node exists and it is  less than the parent node , Which is as per Rule 2 should not be true.

This way , recursively traversing down the tree and checking for all the nodes .  If all the nodes satisfy the condition it means our binary tree is a Binary search tree !!

You can try this program , along with the creation of binary search tree for checking the result !!



No comments:

Post a Comment