Skip to content

Commit

Permalink
done
Browse files Browse the repository at this point in the history
  • Loading branch information
Kamini8707 committed Oct 28, 2024
1 parent 76e3e4a commit ffb45c6
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
51 changes: 51 additions & 0 deletions Binary Tree Algorithms/Check if a Tree is a BST or not/Program.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#include <stdio.h>
#include <stdbool.h>
#include <limits.h>

struct Node {
int data;
struct Node* left;
struct Node* right;
};

// Function to create a new node
struct Node* newNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}

// Utility function to check BST properties
bool isBSTUtil(struct Node* node, int min, int max) {
if (node == NULL)
return true;

// Node's value must lie between min and max
if (node->data <= min || node->data >= max)
return false;

// Recursively check left and right subtrees
return isBSTUtil(node->left, min, node->data) &&
isBSTUtil(node->right, node->data, max);
}

// Main function to check if a tree is a BST
bool isBST(struct Node* root) {
return isBSTUtil(root, INT_MIN, INT_MAX);
}

int main() {
struct Node* root = newNode(10);
root->left = newNode(5);
root->right = newNode(20);
root->left->left = newNode(3);
root->left->right = newNode(8);

if (isBST(root))
printf("The tree is a Binary Search Tree\n");
else
printf("The tree is not a Binary Search Tree\n");

return 0;
}
19 changes: 19 additions & 0 deletions Binary Tree Algorithms/Check if a Tree is a BST or not/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
The function recursively verifies that each node’s value lies within a specific range, ensuring all nodes in the left subtree are less and all nodes in the right subtree are greater than the current node.

Explanation of the Code

isBSTUtil Function:
->This recursive utility function checks whether each node’s value is within a specific range (min to max).
->It checks if the current node's value violates the range conditions.
->It then recursively checks left and right subtrees with updated ranges to maintain BST constraints.

isBST Function:
->This function initializes the range for the root node using INT_MIN and INT_MAX, covering all integer values.

Main Function:
->We create a sample tree and test if it’s a BST by calling isBST.

This approach runs in O(n)

O(n) time complexity, where n is the number of nodes, and it uses O(h) space for recursion, where
h is the height of the tree.

0 comments on commit ffb45c6

Please sign in to comment.