Saturday, January 30, 2016

Determine if a Binary Tree is a Binary Search Tree (BST)

Determine if a Binary Tree is a Binary Search Tree (BST)


Problem:
Determine if a given binary tree is a Binary Search Tree (BST) or not.
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
bool isBSTHelper(BTNode T, int min, int max) {
  if (T == null) return true;
  if (min < T.element && T.element < max)
    return isBSTHelper(T.left, min, T.element) &&
           isBSTHelper(T.right, T.element, max);
  else
    return false;
}
  
bool isBST(BTNode root) { 
  return isBSTHelper(root, INT_MIN, INT_MAX);
}

 public boolean isValidBST(TreeNode root) {
        return isBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
   
    public boolean isBST(TreeNode root, long min, long max) {
        if(root==null)
            return true;
        if (root.val >= max || root.val <= min)
            return false;
        return isBST(root.left, min, root.val)&&isBST(root.right, root.val, max);
     
    }

No comments:

Post a Comment