Binary Search Tree Check
A binary tree is a non-linear data structure. It is called a binary tree because each node has at most two children. These children are called left children and right children. For a binary tree to be a BST, it must satisfy the following properties.
- All nodes in the left subtree are smaller than the root node.
- All nodes in the right subtree are larger than the root node.
- The left and right subtrees must also be binary search trees.
Algorithm for testing whether a binary tree is a binary search tree
Algorithm 1
In this approach, we treat each node as the root of its subtree and check if the left subtree contains any element greater than the root value and if the right subtree contains any element less than the root value. To find the maximum and minimum element, we have to use two separate functions getMin()
and getMax()
.
getMin()
-
Initialize
temp
toroot
. -
When
temp
there is aleft
, do the following.-
Set
temp
totemp->left
, that is, move left to find the smallest element.
-
Set
-
Returns
temp->val
the minimum value of the subtree.
getMax()
-
Initialize
temp
toroot
. -
When
temp
there is aright
, do the following.-
Set
temp
totemp->right
, that is, move right to find the largest element.
-
Set
-
Returns
temp->val
the maximum value of the subtree.
isBST(root)
-
If
root
yesNULL
, returntrue
. -
Find the maximum element in the left subtree by calling getMax(root->left)
maxm
. -
Find the minimum element in the right subtree by calling getMin(root->right)
minm
. -
If the root element is less than
maxm
or greater thanminm
, returns false. -
Recursively check all nodes by calling
isBST(root->left)
andisBST(root->right)
. If both recursive calls return true, then the tree is a BST and return true, otherwise return false.
The above algorithm tells us whether a tree is a BST, but it is extremely slow. Functions getMin()
and getMax()
have a worst-case time complexity of n2 O(n)
, and they are n
called for n2 nodes, making the total time complexity O(n2 ) .
Algorithm 2
This algorithm improves on the previous one by not repeating the calculations. The previous method called getMin()
and for each node getMax()
. This method improves on the above method by keeping track of the minimum and maximum allowed values as we traverse the nodes.
isBST(root)
-
Initialize two variables
min
to beINT_MIN
andmax
to beINT_MAX
. -
Call
isBST(root,min,max)
.
isBST(root, min, max)
-
If
root
yesNULL
, returntrue
. -
If
min
>root->data
, then the BST property is violated and false is returned. -
If
max
<root->data
, then the BST property is violated and false is returned. isBST(root->left, min, root->data-1)
The left subtree is checked recursively by calling (passingmin
androot->data - 1
as parameters changes the valid range of the BST in the left subtree), andisBST(root->right, root->data+1, max)
the right subtree is checked recursively by calling (passingroot->data + 1
andmax
as parameters changes the valid range of the BST in the right subtree).-
If both recursive calls return
true
, then the tree is a BST, returntrue
.
The time complexity of this algorithm is O(n)
, which is a significant improvement over the previous method.
Algorithm 3
This algorithm avoids the use of INT_MIN
and in the above algorithm INT_MAX
and uses two pointers l
and r
instead.
isBST(root)
-
Initialize two nodes
l
andr
to beNULL
. -
Call
isBST(root, l, r)
. (Overloaded function call)
isBST(root, l, r)
-
If
root
yesNULL
, returntrue
. -
If
l
is notNULL
andl->data
>=root->data
, then the BST property is violated and false is returned. -
If
r
is notNULL
andr->data
<=root->data
, then the BST property is violated and false is returned. - Recursively check the left subtree
by calling
isBST(root->left, left, root)
(passing root as the third argument changes the subtree's minimum limit) and calling (passing root as the second argument changes the subtree's maximum limit).isBST(root->right, root, right)
-
If both recursive calls return
true
, then the tree is a BST, returntrue
.
Algorithm 4:
The inorder traversal of a binary search tree returns the elements in sorted order. We can use this property to check whether a binary tree is a BST or not. If all the elements in the inorder traversal are not in ascending order, then the given tree is not a binary search tree.
isBST(root)
prev
Initialize the variable toINT_MIN
.prev
Used to check if the current node is greater thanprev
, thus proceeding in sorted order.-
Call
isBST(root, prev)
. (Overload function Call).
isBST(root,prev)
-
If
root
yesNULL
, returntrue
. -
Recursively
isBST(root->left, prev)
check the left subtree by . If it doesfalse
, return false. -
If
root->data
<=prev
, the ascending order is violated and false is returned. -
Update
prev->data
toroot->data
. -
Recursively
isBST(root->right, prev)
check the right subtree by . If it doesfalse
, return false. - Otherwise, return true.
Algorithm implementation method to check whether a binary tree is a binary search tree
Algorithm 1
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int x) {
this->data = x;
this->left = this->right = NULL;
}
};
int getMin(Node* root)
{
while (root->left) {
root = root->left;
}
return root->data;
}
int getMax(Node* root)
{
while (root->right) {
root = root->right;
}
return root->data;
}
bool isBST( Node* root)
{
if (root == NULL)
return true;
if (root->left != NULL && getMax(root->left) > root->data)
return false;
if (root->right != NULL && getMin(root->right) < root->data)
return false;
if (!isBST(root->left) || !isBST(root->right))
return false;
return true;
}
int main()
{
Node *root = new Node(6);
root -> left = new Node(3);
root -> right = new Node(9);
root -> left -> left = new Node(1);
root -> left -> right = new Node(5);
root -> right -> left = new Node(7);
root -> right -> right = new Node(11);
if (isBST(root)) {
cout << "This binary tree is a BST." << endl;
}
else {
cout << "This binary tree is not a BST." << endl;
}
return 0;
}
Algorithm 2
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int x) {
this->data = x;
this->left = this->right = NULL;
}
};
bool isBST(Node* root, int min, int max)
{
if (root == NULL)
return 1;
if (root->data < min || root->data > max)
return 0;
return
isBST(root->left, min, root->data - 1) &&
isBST(root->right, root->data + 1, max);
}
bool isBST( Node* root)
{
return isBST(root, INT_MIN, INT_MAX);
}
int main()
{
Node *root = new Node(6);
root -> left = new Node(3);
root -> right = new Node(9);
root -> left -> left = new Node(1);
root -> left -> right = new Node(5);
root -> right -> left = new Node(7);
root -> right -> right = new Node(11);
if (isBST(root)) {
cout << "This binary tree is a BST." << endl;
}
else {
cout << "This binary tree is not a BST." << endl;
}
return 0;
}
Algorithm 3
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int x) {
this->data = x;
this->left = this->right = NULL;
}
};
bool isBST(Node* root, Node* l, Node* r)
{
if (root == NULL)
return true;
if (l != NULL and root->data <= l->data)
return false;
if (r != NULL and root->data >= r->data)
return false;
return isBST(root->left, l, root) && isBST(root->right, root, r);
}
bool isBST( Node* root)
{
Node* l = NULL;
Node* r = NULL;
return isBST(root, l, r);
}
int main()
{
Node *root = new Node(6);
root -> left = new Node(3);
root -> right = new Node(9);
root -> left -> left = new Node(1);
root -> left -> right = new Node(5);
root -> right -> left = new Node(7);
root -> right -> right = new Node(11);
if (isBST(root)) {
cout << "This binary tree is a BST." << endl;
}
else {
cout << "This binary tree is not a BST." << endl;
}
return 0;
}
Algorithm 4
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int x) {
this->data = x;
this->left = this->right = NULL;
}
};
bool isBST(Node* root, int& prev)
{
if (!root) return true;
if (!isBST(root->left, prev))
return false;
if (root->data <= prev)
return false;
prev = root->data;
return isBST(root->right, prev);
}
bool isBST(Node* root)
{
int prev = INT_MIN;
return isBST(root, prev);
}
int main()
{
Node *root = new Node(6);
root -> left = new Node(3);
root -> right = new Node(9);
root -> left -> left = new Node(1);
root -> left -> right = new Node(5);
root -> right -> left = new Node(7);
root -> right -> right = new Node(11);
if (isBST(root)) {
cout << "This binary tree is a BST." << endl;
}
else {
cout << "This binary tree is not a BST." << endl;
}
return 0;
}
Complexity Analysis
Time Complexity
- Average situation
To check if a given binary tree is a BST, we have to traverse all n
the nodes, since a node that does not meet the property will result in the tree not being a BST. Therefore, the time complexity is [Big Theta]: O(n)
.
- Best Case
The time complexity for the best case is O(n)
. It is the same as the time complexity for the average case.
- Worst case scenario
The worst case time complexity is O(n)
. It is the same as the best case time complexity.
Space complexity
Due to the additional space required for the recursive calls, the space complexity of this algorithm is O(n)
.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Learning the Sorting Algorithm - Insertion Sort (Concepts)
Publish Date:2025/03/19 Views:96 Category:ALGORITHM
-
What is "insertion sort"? The concept is as follows: each time a record to be sorted is inserted into the previously sorted sequence according to its key size, until all records are inserted. Concepts are always somewhat abstract, and can a
Learning path of sorting algorithm - direct insertion sort
Publish Date:2025/03/19 Views:176 Category:ALGORITHM
-
This article follows up on Insertion Sort (Concepts) and presents the implementation steps and code for direct insertion sort. Since the Concepts section already has a large number of illustrations, it would be a bit long-winded to provide
Learning the sorting algorithm - Binary Insertion Sort
Publish Date:2025/03/19 Views:143 Category:ALGORITHM
-
This article follows the insertion sort (concept article) and presents the implementation steps and implementation code of the binary insertion sort Binary Insertion Sort Algorithm Steps Treat the first element of the first sequence to be s
The road to learning sorting algorithms - table insertion sort
Publish Date:2025/03/19 Views:194 Category:ALGORITHM
-
Table insertion sort was briefly mentioned in Insertion sort (concept) . I briefly summarized it and wrote this article. You can refer to it if you need it. Table insertion sort, as the name implies, uses an index table to sort the original
The road to learning sorting algorithms - Hill sort
Publish Date:2025/03/19 Views:52 Category:ALGORITHM
-
Hill sort is named after the designer of the algorithm, Hill. It is an improvement of Hill on the basis of insertion sort and can be said to be a special insertion sort. Here are the properties of insertion sort: First of all, the insertion
Things about the singleton design pattern
Publish Date:2025/03/19 Views:53 Category:ALGORITHM
-
The singleton design pattern is one of the most commonly used design patterns. The singleton design pattern, just by its name, you can roughly know its meaning. Single means one; instance means instance object. So a singleton has only one i
The road to learning sorting algorithms - merge sort
Publish Date:2025/03/19 Views:158 Category:ALGORITHM
-
Let's first look at the definition of merge sort Merge sort is an effective sorting algorithm based on the merge operation. This algorithm is a very typical application of the Divide and Conquer method. Merge the ordered subsequences to obt
The road to learning sorting algorithms - merge sort (non-recursive implementatio
Publish Date:2025/03/19 Views:189 Category:ALGORITHM
-
In the article "Merge Sort", we introduced the principles and operation steps of merge sort, and finally implemented the sorting algorithm using PHP code. In the program, we used the principle of recursion to implement the algorithm. In fac
The road to learning sorting algorithms - quick sort
Publish Date:2025/03/19 Views:122 Category:ALGORITHM
-
Quick sort is a sorting algorithm developed by Tony Hall. On average, sorting n items requires O(n log n) comparisons. In the worst case, O(n2) comparisons are required, but this is uncommon. In fact, quick sort is often significantly faste