Question

Consider the following BNode class: class BNode { int val; BNode left, right; ... boolean isBST(BNode...

Consider the following BNode class:

class BNode {

int val;

BNode left, right;
...

boolean isBST(BNode u){...}
boolean isBST(int min, BNode u, int max){...}

}

Note that our BNodes do not have parent pointers! It has a method isBST(u) that returns true iff the subtree rooted at u is a BST. Please write the code for isBST(u) and its helper method isBST(min, u, max) which will return false if the keys in the subtree at u do not lie in the range (min, max). The helper method must be recursive.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

int isBST(BNode  root)

{

    // if the tree is empty

    if (root == null)

        return true;

    // if the current node disobeys the BST property

    // use the isBST(min, u,max) function to check if each key in left subtree

    // is smaller than root node

    if (root.left != null && this.isBST( Integer.MIN_VALUE , root.left , root.value) )

        return false;

    // if the current node disobeys the BST property

    // use the isBST(min, u,max) function to check if each key in right subtree

    // is greater than root node

    if (root.right != null && this.isBST( root.value , root.right , Integer.MAX_VALUE))

        return false;

    // recursively check if the right and left subtree also are in BST

    if( isBST(root.left) != true || isBST(root.right) != true )

        return false;

    // if the tree is BST

    return true;

}

boolean isBST(int min, BNode u, int max)

{

    if( u == null )

        return true;

   

    // if the current node is outside the range

    if( u.value < min || u.value > max )

        return false;

   

    // recursively check if the right and left subtree also are in BST

    if( isBST(min, root.left, max) != true || isBST(min, root.right, max) != true )

        return false;

   

    return true;

}

Add a comment
Know the answer?
Add Answer to:
Consider the following BNode class: class BNode { int val; BNode left, right; ... boolean isBST(BNode...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT