check if a tree is a bst

int inorderCheck( TreeNode *root, int *last )
{
if( root == NULL )
{
*last  = INT_MIN;
return 1;
}

int left = inorderCheck( root->left, last );
if( root->data > *last && *last != null )
{
*last = root->data;
}
else
{
printf(“not a bst”);
return 0;
}
int right = inoderCheck( root->right, last );

return left && right;
}

sol 2: better, more natural by pre-order
int preorderCheck( TreeNode *root )
{
//NULL check
if( root == NULL )
{
return 1;
}
// single node without child
else if( root->left == NULL && root->right == NULL )
{
return 1;
}
else if( root->left == NULL )
{
return root->data right->data; 
}
else if( root->right == NULL )
{
return root->data > root->right->data;
}
else if( root.data > root->left->data && root.data right->data )
{
return preOrder( root->left) && preOrder( root->right );
}
else
{
return 0;
}
}

Advertisements
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s