Thursday, 3 April 2014

IsBST(Check wether the given tree is BST)

To Check whether given tree is BST or not, we need to change if its left sub tree has any value greater than root or right sub tree has any value less than root.

Ex:
                             10
                 5                        20
            3         15         18           25

If we need node by node comparion with left/rgith sub-tress, we will get true for the above tree, where as we have 15, which is on the left sub tree and is greater than the root(10).

To solve this use one of the following approaches:
Approach 1:
========
bool isBST(Node *root)
{
return BSTUtil(root,INT_MIN,INT_MAX)
}
bool BSTUtil(Node *root, int min,int max)
{
if(root==NULL)
return true;

if(root->data<min || root->data>max)
return false;
return BSTUtil(root->left,min,root->data) && BSTUtil(root->right,root->data,max);
}

We call multiple methods in above approach , which gives the correct results. To make it even simpler use the following approach.

  • Go to the left most leaf node in the tree 
  • Check that is value is greater than the INT_MIN(lastData);
  • Assign the node data to lastData(which is current min value)
  • Go back to parent node, as it is the leaf and checks it value greater than lastData
  • Assign root->data to lastData
  • Now go to the right of the node(if it has) and check its data is greater than the lastData.
Approach 2:
========
bool isBST(Node *root)
{
    static int lastData= INT_MIN;
    if(root==NULL)
        return 1;
    isBST(root->left);
        if(root->data>prev)
            lastData=root->data;
        else{
            cout<<"NOT BST"<<endl;
            return 0;
        }
    return isBST(root->right);
}

No comments:

Post a Comment

AWS Data Pipeline Services

https://www.youtube.com/watch?v=tykcCf-Zz1M