September 19, 2013

Interview Question - Determine if a Tree is a Binary Search Tree

Well it's interview season.  That basically means it's the time of year I spend way more time studying for interviews than I do for actual class work.  Which doesn't bode well for my next week of midterms but I guess getting a summer internship is more important in the long run than acing one midterm.

Here's a question I remember I attempted a year ago, gave up, tried again recently, and got a working solution:

Determine if a binary tree is a binary search tree.
Solution in C#.  I defined previous and current as ints above because I didn't want to distract from the logic of the code.

const int previous = 1;
const int current = 0;

static bool IsBSTHelper(BSTNode node, int[] a)
{
    if (node == null) return true;

    var isValidBST = IsBSTHelper(node.left,
a);

   
a[previous] = a[current];
   
a[current] = node.data;

    if (
a[current] < a[previous])
    {
        return false;
    }

    return isValidBST && IsBSTHelper(node.right,
a);
}

static bool IsBST(BSTNode root)
{
    return IsBSTHelper(root, new int[] {int.MinValue, int.MinValue});
}

I started out with the classic pre-order tree traversal.  Since it prints out the elements in the right order, I figured I would save the last printed element in the recursive call and compare it with the next printed element.  I was running into problems with that until I decided to use an array of two ints to store the values instead.  And now.. it works for all of my test cases.

Here I assume the tree is nice.  This wouldn't return false if a tree has more than two children per node, or if the tree has a loop.