Saturday, June 15, 2013

Check if the given binary tree is BST or not

Problem:
Check if the given binary tree is BST or not.

Solution:


public boolean isBSTMain(Node root) {
 return (isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE));
}

private boolean isBST(Node node, int min, int max) {
 if (node == null)  return true;
 
 if (node.data < min || node.data > max) return false;

 // left should be in range min...node.data
 boolean leftOk = isBST(node.left, min, node.data);
 if (!leftOk) return false;

 // right should be in range node.data..max
 return isBST(node.right, node.data, max);
}


Complexity:
time - O(n)
space - O(n) (the stack space for the recursion)
Links and credits:
http://www.careercup.com/question?id=19685712

No comments:

Post a Comment