#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
int isBSTUtil(struct node* node, int min, int max);
/* Returns true if the given tree is a binary search tree
(efficient version). */
int isBST(struct node* node)
{
return(isBSTUtil(node, INT_MIN, INT_MAX));
}
/* Returns true if the given tree is a BST and its
values are >= min and <= max. */
int isBSTUtil(struct node* node, int min, int max)
{
/* an empty tree is BST */
if (node==NULL)
return 1;
/* false if this node violates the min/max constraint */
if (node->data < min || node->data > max)
return 0;
/* otherwise check the subtrees recursively,
tightening the min or max constraint */
return
isBSTUtil(node->left, min, node->data-1) && // Allow only distinct values
isBSTUtil(node->right, node->data+1, max); // Allow only distinct values
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above functions*/
int main()
{
struct node *root = newNode(4);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(1);
root->left->right = newNode(3);
if(isBST(root))
printf("Is BST");
else
printf("Not a BST");
getchar();
return 0;
}
Code Example |
---|
C :: epita |
C :: typecating in c |
C :: c ausgabe |
C :: nested if example in c |
C :: how to stop aws alb temporarily |
C :: first come first serve |
C :: temperature sensor data |
C :: BSTNode root |
C :: arcolinux |
C :: fraction sum c |
C :: python to java translator online |
C :: syntax of for loop in c stack over flow |
C :: type conversion |
C :: getopt optstr |
C :: command line coursera |
C :: ::template |
C :: Uri/Beecrowd problem no - 1149 solution in C |
C :: C programming statician |
C :: C How to use enums for flags? |
C :: letter in alphabet or not |
C :: formula to find the area of a trapezium in c |
C :: Happy New Year! |
C :: how can i show ant text by onclick |
Dart :: asset image in circle avatar flutter |
Dart :: flutter textspan onclick |
Dart :: delete shared preference flutter |
Dart :: flutter array of strings |
Dart :: how to get first word of a sentence in flutter |
Dart :: Flutter turn string to int |
Dart :: Attribute application@icon value=(@mipmap/launcher_icon) from AndroidManifest.xml:17:9-45 |