Thursday, March 15, 2012

check binary tree being binary search tree

// =========================================================
// 
//       Filename:  bstcheck.cpp
// 
//    Description:  check whether a binary tree is a binary search tree (BST)
// 
//        Version:  1.0
//        Created:  03/15/2012 10:14:03 PM
//       Revision:  none
//       Compiler:  g++
// 
//         Author:  LI YAN (lyan), lyan@cs.ucr.edu
//        Company:  U of California Riverside
//      Copyright:  Copyright (c) 03/15/2012, LI YAN
// 
// =========================================================

#include <cstdio>
using namespace std;

struct node {
    int val;
    node *left, *right;
};

// check left, check right
// also need min and max of this subtree
//
bool checkbst(node *root, int &vmin, int &vmax)
{
    if (root==NULL) return true;
    int a1, b1, a2, b2;
    vmin=vmax=root->val;
    if (root->left != NULL) {
        bool bleft = checkbst(root->left, a1, b1);
        if (!bleft) return false;
        if (b1>root->val) return false;
        vmin = a1;
    }
    if (root->right != NULL) {
        bool bright = checkbst(root->right, a2, b2);
        if (!bright) return false;
        if (a2<root->val) return false;
        vmax = b2;
    }
    return true;
}

void print(node *root)
{
    if (root==NULL) return;
    print(root->left);
    printf(" %d", root->val);
    print(root->right);
}

int main()
{
    node a[100];
    for(int i=0; i<10; ++i) {
        if (2*i+1<10) a[i].left=&a[2*i+1]; 
        else a[i].left = NULL;

        if (2*i+2<10) a[i].right=&a[2*i+2];
        else a[i].right = NULL;
    }
    // expected: true
    int v[] = { 500, 200, 800, 100, 300, 600, 900, 50, 150, 280};
    // expected: false
    //int v[] = { 500, 200, 800, 100, 300, 600, 900, 50, 150, 350}; 
    for(int i=0; i<10; ++i) {
        a[i].val = v[i];
    }

    node *root=&a[0];
    int x, y;
    print(root); putchar('\n');
    bool c = checkbst(root, x, y);
    if (c) puts("true");
    else puts("false");
}

No comments:

Post a Comment