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)Links and credits:
space - O(n) (the stack space for the recursion)
http://www.careercup.com/question?id=19685712
No comments:
Post a Comment