Check if a Binary Tree is BST or not
Last Updated :
17 Feb, 2025
Given the root of a binary tree. Check whether it is a Binary Search Tree or not. A Binary Search Tree (BST) is a node-based binary tree data structure with the following properties.
- All keys in the left subtree are smaller than the root and all keys in the right subtree are greater.
- Both the left and right subtrees must also be binary search trees.
- Each key must be distinct.
[Approach - 1] Using specified range of Min and Max Values - O(n) Time and O(h) Space
The idea is to use a recursive helper function, isBSTUtil(node, min, max) to check whether a subtree (rooted at a given node) is a binary search tree (BST) within a specified range of minimum (min) and maximum (max) values. If it falls outside this range, it violates BST properties, so we return false.
- For the left subtree, we call isBSTUtil() with the updated range as the max is set to (node->data - 1 ) because all values in the left subtree must be smaller than the current node's value.
- For the right subtree, we call isBSTUtil() with the updated range as the min is set to (node->data + 1) because all values in the right subtree must be greater than the current node's value.
Both recursive calls must return true for the entire subtree to be a valid BST.
C++
//Driver Code Starts
// C++ program to check if a tree is BST
// Using specified range of Min and Max Values
#include <iostream>
#include <climits>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = right = nullptr;
}
};
//Driver Code Ends
// Helper function to check if a tree is BST within a given range
bool isBSTUtil(Node* node, int min, int max) {
if (node == nullptr)
return true;
// If the current node's data
// is not in the valid range, return false
if (node->data < min || node->data > max)
return false;
// Recursively check the left and
// right subtrees with updated ranges
return isBSTUtil(node->left, min, node->data - 1) &&
isBSTUtil(node->right, node->data + 1, max);
}
// Function to check if the entire binary tree is a BST
bool isBST(Node* root) {
return isBSTUtil(root, INT_MIN, INT_MAX);
}
//Driver Code Starts
int main() {
// Create a sample binary tree
// 10
// / \
// 5 20
// / \
// 9 25
Node* root = new Node(10);
root->left = new Node(5);
root->right = new Node(20);
root->right->left = new Node(9);
root->right->right = new Node(25);
if (isBST(root))
cout << "True" << endl;
else
cout << "False" << endl;
return 0;
}
//Driver Code Ends
C
//Driver Code Starts
// C program to check if a tree is BST
// Using specified range of Min and Max Values
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
//Driver Code Ends
// Helper function to check if a tree is BST within a given range
bool isBSTUtil(struct Node* node, int min, int max) {
if (node == NULL) return true;
// If the current node's data
// is not in the valid range, return false
if (node->data < min || node->data > max) return false;
// Recursively check the left and
// right subtrees with updated ranges
return isBSTUtil(node->left, min, node->data - 1) &&
isBSTUtil(node->right, node->data + 1, max);
}
// Function to check if the entire binary tree is a BST
bool isBST(struct Node* root) {
return isBSTUtil(root, INT_MIN, INT_MAX);
}
//Driver Code Starts
struct Node* createNode(int value) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = newNode->right = NULL;
return newNode;
}
int main() {
// Create a sample binary tree
// 10
// / \
// 5 20
// / \
// 9 25
struct Node* root = createNode(10);
root->left = createNode(5);
root->right = createNode(20);
root->right->left = createNode(9);
root->right->right = createNode(25);
if (isBST(root))
printf("True");
else
printf("False");
return 0;
}
//Driver Code Ends
Java
//Driver Code Starts
// Java program to check if a tree is BST
// Using specified range of Min and Max Values
class Node {
int data;
Node left, right;
Node(int value) {
data = value;
left = right = null;
}
}
class GfG {
//Driver Code Ends
// Helper function to check if a tree is BST within a given range
static boolean isBSTUtil(Node node, int min, int max) {
if (node == null) return true;
// If the current node's data
// is not in the valid range, return false
if (node.data < min || node.data > max) return false;
// Recursively check the left and
// right subtrees with updated ranges
return isBSTUtil(node.left, min, node.data - 1) &&
isBSTUtil(node.right, node.data + 1, max);
}
// Function to check if the entire binary tree is a BST
static boolean isBST(Node root) {
return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
//Driver Code Starts
public static void main(String[] args) {
// Create a sample binary tree
// 10
// / \
// 5 20
// / \
// 9 25
Node root = new Node(10);
root.left = new Node(5);
root.right = new Node(20);
root.right.left = new Node(9);
root.right.right = new Node(25);
if (isBST(root)) {
System.out.println("True");
}
else {
System.out.println("False");
}
}
}
//Driver Code Ends
Python
#Driver Code Starts
# Python program to check if a tree is BST
# Using specified range of Min and Max Values
class Node:
def __init__(self, value):
self.data = value
self.left = None
self.right = None
#Driver Code Ends
# Helper function to check if a tree is
# BST within a given range
def isBstUtil(node, min_val, max_val):
if node is None:
return True
# If the current node's data
# is not in the valid range, return false
if node.data < min_val or node.data > max_val:
return False
# Recursively check the left and
# right subtrees with updated ranges
return (isBstUtil(node.left, min_val, node.data - 1) and
isBstUtil(node.right, node.data + 1, max_val))
# Function to check if the entire binary tree is a BST
def isBST(root):
return isBstUtil(root, float('-inf'), float('inf'))
#Driver Code Starts
if __name__ == "__main__":
# Create a sample binary tree
# 10
# / \
# 5 20
# / \
# 9 25
root = Node(10)
root.left = Node(5)
root.right = Node(20)
root.right.left = Node(9)
root.right.right = Node(25)
if isBST(root):
print("True")
else:
print("False")
#Driver Code Ends
C#
//Driver Code Starts
// C# program to check if a tree is BST
// Using specified range of Min and Max Values
using System;
class Node {
public int data;
public Node left, right;
public Node(int value) {
data = value;
left = right = null;
}
}
class GfG {
//Driver Code Ends
// Helper function to check if a tree is BST within a given range
static bool isBSTUtil(Node node, int min, int max) {
if (node == null) return true;
// If the current node's data
// is not in the valid range, return false
if (node.data < min || node.data > max) return false;
// Recursively check the left and
// right subtrees with updated ranges
return isBSTUtil(node.left, min, node.data - 1) &&
isBSTUtil(node.right, node.data + 1, max);
}
// Function to check if the entire binary tree is a BST
static bool isBST(Node root) {
return isBSTUtil(root, int.MinValue, int.MaxValue);
}
//Driver Code Starts
static void Main() {
// Create a sample binary tree
// 10
// / \
// 5 20
// / \
// 9 25
Node root = new Node(10);
root.left = new Node(5);
root.right = new Node(20);
root.right.left = new Node(9);
root.right.right = new Node(25);
if (isBST(root)) {
Console.WriteLine("True");
}
else {
Console.WriteLine("False");
}
}
}
//Driver Code Ends
JavaScript
//Driver Code Starts
// JavaScript program to check if a tree is BST
// Using specified range of Min and Max Values
class Node {
constructor(value) {
this.data = value;
this.left = this.right = null;
}
}
//Driver Code Ends
// Helper function to check if a tree is BST
// within a given range
function isBSTUtil(node, min, max) {
if (node === null) return true;
// If the current node's data
// is not in the valid range, return false
if (node.data < min || node.data > max) return false;
// Recursively check the left and
// right subtrees with updated ranges
return isBSTUtil(node.left, min, node.data - 1) &&
isBSTUtil(node.right, node.data + 1, max);
}
// Function to check if the entire binary tree is a BST
function isBST(root) {
return isBSTUtil(root, -Infinity, Infinity);
}
//Driver Code Starts
// Driver Code
// Create a sample binary tree
// 10
// / \
// 5 20
// / \
// 9 25
const root = new Node(10);
root.left = new Node(5);
root.right = new Node(20);
root.right.left = new Node(9);
root.right.right = new Node(25);
if (isBST(root)) {
console.log("True");
} else {
console.log("False");
}
//Driver Code Ends
Time Complexity: O(n), where n is the number of nodes, as each node is visited once.
Auxiliary Space: O(h), where h is the height of the tree, due to recursive calls (worst case O(n) for a skewed tree, O(log n) for a balanced tree).
[Approach - 2] Using Inorder Traversal - O(n) Time and O(h) Space
The idea is to use inorder traversal of a binary search tree, in which the output values are sorted in ascending order. After generating the inorder traversal of the given binary tree, we can check if the values are sorted or not.
Note: We can avoid the use of an Auxiliary Array. While doing In-Order traversal, we can keep track of previously visited value. If the value of the currently visited node is less than the previous value, then the tree is not BST.
C++
//Driver Code Starts
// C++ program to check if a tree is BST
// using Inorder Traversal
#include <iostream>
#include <climits>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = right = nullptr;
}
};
//Driver Code Ends
// Recursive Function for inorder traversal
bool inorder(Node* root, int &prev) {
if (!root)
return true;
// Recursively check the left subtree
if (!inorder(root->left, prev))
return false;
// Check the current node value against the previous value
if (prev >= root->data)
return false;
// Update the previous value to the current node's value
prev = root->data;
// Recursively check the right subtree
return inorder(root->right, prev);
}
// Function to check if the tree is a valid BST
bool isBST(Node* root) {
int prev = INT_MIN;
return inorder(root, prev);
}
//Driver Code Starts
int main() {
// Create a sample binary tree
// 10
// / \
// 5 20
// / \
// 9 25
Node* root = new Node(10);
root->left = new Node(5);
root->right = new Node(20);
root->right->left = new Node(9);
root->right->right = new Node(25);
if (isBST(root))
cout << "True" << endl;
else
cout << "False" << endl;
return 0;
}
//Driver Code Ends
C
//Driver Code Starts
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// Definition for a binary tree node
struct Node {
int data;
struct Node* left;
struct Node* right;
};
//Driver Code Ends
// Recursive Function for inorder traversal
int isValidBST(struct Node* root, int* prev) {
if (root == NULL) return 1;
// Recursively check the left subtree
if (!isValidBST(root->left, prev)) return 0;
// Check the current node value against the previous value
if (*prev >= root->data) return 0;
// Update the previous value to the current node's value
*prev = root->data;
// Recursively check the right subtree
return isValidBST(root->right, prev);
}
// Wrapper function to initialize previous value
// and call the recursive function
int isBST(struct Node* root) {
int prev = INT_MIN;
return isValidBST(root, &prev);
}
//Driver Code Starts
struct Node* createNode(int value) {
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->data = value;
node->left = NULL;
node->right = NULL;
return node;
}
int main() {
// Create a sample binary tree
// 10
// / \
// 5 20
// / \
// 9 25
struct Node* root = createNode(10);
root->left = createNode(5);
root->right = createNode(20);
root->right->left = createNode(9);
root->right->right = createNode(25);
if (isBST(root))
printf("True");
else
printf("False");
return 0;
}
//Driver Code Ends
Java
//Driver Code Starts
// Java program to check if a tree is BST using Inorder Traversal
class Node {
int data;
Node left, right;
Node(int value) {
data = value;
left = right = null;
}
}
class GfG {
//Driver Code Ends
// Recursive Function for inorder traversal
static boolean inorder(Node root, int[] prev) {
if (root == null)
return true;
// Recursively check the left subtree
if (!inorder(root.left, prev))
return false;
// Check the current node value against the previous value
if (prev[0] >= root.data)
return false;
// Update the previous value to the current node's value
prev[0] = root.data;
// Recursively check the right subtree
return inorder(root.right, prev);
}
// Function to check if the tree is a valid BST
static boolean isBST(Node root) {
int[] prev = {Integer.MIN_VALUE};
return inorder(root, prev);
}
//Driver Code Starts
public static void main(String[] args) {
// Create a sample binary tree
// 10
// / \
// 5 20
// / \
// 9 25
Node root = new Node(10);
root.left = new Node(5);
root.right = new Node(20);
root.right.left = new Node(9);
root.right.right = new Node(25);
if (isBST(root)) {
System.out.println("True");
}
else {
System.out.println("False");
}
}
}
//Driver Code Ends
Python
#Driver Code Starts
# Python program to check if a tree is BST using Inorder Traversal
class Node:
def __init__(self, value):
self.data = value
self.left = None
self.right = None
#Driver Code Ends
# Recursive Function for inorder traversal
def inorder(root, prev):
if root is None:
return True
# Recursively check the left subtree
if not inorder(root.left, prev):
return False
# Check the current node value against the previous value
if prev[0] >= root.data:
return False
# Update the previous value to the current node's value
prev[0] = root.data
# Recursively check the right subtree
return inorder(root.right, prev)
# Function to check if the tree is a valid BST
def isBST(root):
prev = [float('-inf')]
return inorder(root, prev)
#Driver Code Starts
if __name__ == "__main__":
# Create a sample binary tree
# 10
# / \
# 5 20
# / \
# 9 25
root = Node(10)
root.left = Node(5)
root.right = Node(20)
root.right.left = Node(9)
root.right.right = Node(25)
if isBST(root):
print("True")
else:
print("False")
#Driver Code Ends
C#
//Driver Code Starts
// C# program to check if a tree is BST using Inorder Traversal
using System;
class Node {
public int data;
public Node left, right;
public Node(int value) {
data = value;
left = right = null;
}
}
class GfG {
//Driver Code Ends
// Recursive Function for inorder traversal
static bool inorder(Node root, ref int prev) {
if (root == null)
return true;
// Recursively check the left subtree
if (!inorder(root.left, ref prev))
return false;
// Check the current node value against the previous value
if (prev >= root.data)
return false;
// Update the previous value to the current node's value
prev = root.data;
// Recursively check the right subtree
return inorder(root.right, ref prev);
}
// Function to check if the tree is a valid BST
static bool isBST(Node root) {
int prev = int.MinValue;
return inorder(root, ref prev);
}
//Driver Code Starts
static void Main() {
// Create a sample binary tree
// 10
// / \
// 5 20
// / \
// 9 25
Node root = new Node(10);
root.left = new Node(5);
root.right = new Node(20);
root.right.left = new Node(9);
root.right.right = new Node(25);
if (isBST(root)) {
Console.WriteLine("True");
}
else {
Console.WriteLine("False");
}
}
}
//Driver Code Ends
JavaScript
//Driver Code Starts
// JavaScript program to check if a tree is BST
// using Inorder Traversal
class Node {
constructor(value) {
this.data = value;
this.left = null;
this.right = null;
}
}
//Driver Code Ends
// Recursive Function for inorder traversal
function inorder(root, prev) {
if (root === null)
return true;
// Recursively check the left subtree
if (!inorder(root.left, prev))
return false;
// Check the current node value against the previous value
if (prev[0] >= root.data)
return false;
// Update the previous value to the current node's value
prev[0] = root.data;
// Recursively check the right subtree
return inorder(root.right, prev);
}
// Function to check if the tree is a valid BST
function isBST(root) {
let prev = [-Infinity];
return inorder(root, prev);
}
//Driver Code Starts
// Driver Code
// Create a sample binary tree
// 10
// / \
// 5 20
// / \
// 9 25
const root = new Node(10);
root.left = new Node(5);
root.right = new Node(20);
root.right.left = new Node(9);
root.right.right = new Node(25);
if (isBST(root)) {
console.log("True");
} else {
console.log("False");
}
//Driver Code Ends
Time Complexity: O(n), where n is the number of nodes, as each node is visited once in inorder traversal.
Auxiliary Space: O(h), where h is the height of the tree, due to recursive calls (worst case O(n) for a skewed tree, O(log n) for a balanced tree).
[Approach - 3] Using Morris Traversal - O(n) Time and O(1) Space
The idea is to use Morris Traversal for checking if a binary tree is a Binary Search Tree (BST) without using extra space for storing the inorder traversal.
Follow the steps below to solve the problem:
- Start with the root node and traverse the tree while maintaining a pointer to the current node.
- For each node, find its inorder predecessor (the rightmost node in its left subtree). Use this node to temporarily link back to the current node.
- If the left child exists, create a temporary thread from the inorder predecessor to the current node.
- If the left child does not exist, process the current node's data and move to its right child.
- Once you visit the current node, restore the tree by removing the temporary thread. Check the inorder property and proceed to the right child.
- Compare the current node’s value with the previously visited node’s value.
- Continue this process until all nodes are visited. If all nodes satisfy the BST property, then the tree is a BST.
C++
//Driver Code Starts
// C++ program to check if a tree is
// BST using Morris Traversal
#include <iostream>
#include <climits>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = right = nullptr;
}
};
//Driver Code Ends
// Function to check if the binary tree is a BST using Morris Traversal
bool isBST(Node* root) {
Node* curr = root;
Node* pre = nullptr;
int prevValue = INT_MIN;
while (curr != nullptr) {
if (curr->left == nullptr) {
// Process curr node
if (curr->data <= prevValue) {
// Not in ascending order
return false;
}
prevValue = curr->data;
curr = curr->right;
} else {
// Find the inorder predecessor of curr
pre = curr->left;
while (pre->right != nullptr && pre->right != curr) {
pre = pre->right;
}
if (pre->right == nullptr) {
// Create a temporary thread to the curr node
pre->right = curr;
curr = curr->left;
} else {
// Remove the temporary thread
pre->right = nullptr;
// Process the curr node
if (curr->data <= prevValue) {
// Not in ascending order
return false;
}
prevValue = curr->data;
curr = curr->right;
}
}
}
return true;
}
//Driver Code Starts
int main() {
// Create a sample binary tree
// 10
// / \
// 5 20
// / \
// 9 25
Node* root = new Node(10);
root->left = new Node(5);
root->right = new Node(20);
root->right->left = new Node(9);
root->right->right = new Node(25);
if (isBST(root))
cout << "True" << endl;
else
cout << "False" << endl;
return 0;
}
//Driver Code Ends
C
//Driver Code Starts
// C program to check if a tree is BST
// using Morris Traversal
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
//Driver Code Ends
// Function to check if the binary tree is
// a BST using Morris Traversal
int isBST(struct Node* root) {
struct Node* curr = root;
struct Node* pre;
int prevValue = INT_MIN;
while (curr != NULL) {
if (curr->left == NULL) {
// Process curr node
if (curr->data <= prevValue) {
// Not in ascending order
return 0;
}
prevValue = curr->data;
curr = curr->right;
} else {
// Find the inorder predecessor of curr
pre = curr->left;
while (pre->right != NULL && pre->right != curr) {
pre = pre->right;
}
if (pre->right == NULL) {
// Create a temporary thread to the curr node
pre->right = curr;
curr = curr->left;
} else {
// Remove the temporary thread
pre->right = NULL;
// Process the curr node
if (curr->data <= prevValue) {
// Not in ascending order
return 0;
}
prevValue = curr->data;
curr = curr->right;
}
}
}
return 1;
}
//Driver Code Starts
struct Node* createNode(int value) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = newNode->right = NULL;
return newNode;
}
int main() {
// Create a sample binary tree
// 10
// / \
// 5 20
// / \
// 9 25
struct Node* root = createNode(10);
root->left = createNode(5);
root->right = createNode(20);
root->right->left = createNode(9);
root->right->right = createNode(25);
if (isBST(root))
printf("True");
else
printf("False");
return 0;
}
//Driver Code Ends
Java
//Driver Code Starts
// Java program to check if a tree is
// BST using Morris Traversal
class Node {
int data;
Node left, right;
Node(int value) {
data = value;
left = right = null;
}
}
class GfG {
//Driver Code Ends
// Function to check if the binary tree
// is a BST using Morris Traversal
static boolean isBST(Node root) {
Node curr = root;
Node pre;
int prevValue = Integer.MIN_VALUE;
while (curr != null) {
if (curr.left == null) {
// Process curr node
if (curr.data <= prevValue) {
// Not in ascending order
return false;
}
prevValue = curr.data;
curr = curr.right;
} else {
// Find the inorder predecessor of curr
pre = curr.left;
while (pre.right != null && pre.right != curr) {
pre = pre.right;
}
if (pre.right == null) {
// Create a temporary thread to the curr node
pre.right = curr;
curr = curr.left;
} else {
// Remove the temporary thread
pre.right = null;
// Process the curr node
if (curr.data <= prevValue) {
// Not in ascending order
return false;
}
prevValue = curr.data;
curr = curr.right;
}
}
}
return true;
}
//Driver Code Starts
public static void main(String[] args) {
// Create a sample binary tree
// 10
// / \
// 5 20
// / \
// 9 25
Node root = new Node(10);
root.left = new Node(5);
root.right = new Node(20);
root.right.left = new Node(9);
root.right.right = new Node(25);
if (isBST(root)) {
System.out.println("True");
}
else {
System.out.println("False");
}
}
}
//Driver Code Ends
Python
#Driver Code Starts
# Python program to check if a tree is BST using Morris Traversal
class Node:
def __init__(self, value):
self.data = value
self.left = None
self.right = None
#Driver Code Ends
# Function to check if the binary tree is a
# BST using Morris Traversal
def isBST(root):
curr = root
prevValue = float('-inf')
while curr:
if curr.left is None:
# Process curr node
if curr.data <= prevValue:
# Not in ascending order
return False
prevValue = curr.data
curr = curr.right
else:
# Find the inorder predecessor of curr
pre = curr.left
while pre.right and pre.right != curr:
pre = pre.right
if pre.right is None:
# Create a temporary thread to the curr node
pre.right = curr
curr = curr.left
else:
# Remove the temporary thread
pre.right = None
# Process the curr node
if curr.data <= prevValue:
# Not in ascending order
return False
prevValue = curr.data
curr = curr.right
return True
#Driver Code Starts
if __name__ == "__main__":
# Create a sample binary tree
# 10
# / \
# 5 20
# / \
# 9 25
root = Node(10)
root.left = Node(5)
root.right = Node(20)
root.right.left = Node(9)
root.right.right = Node(25)
if isBST(root):
print("True")
else:
print("False")
#Driver Code Ends
C#
//Driver Code Starts
// C# program to check if a tree is BST
// using Morris Traversal
using System;
class Node {
public int data;
public Node left, right;
public Node(int value) {
data = value;
left = right = null;
}
}
class GfG {
//Driver Code Ends
// Function to check if the binary tree is a BST
// using Morris Traversal
static bool isBST(Node root) {
Node curr = root;
Node pre;
int prevValue = int.MinValue;
while (curr != null) {
if (curr.left == null) {
// Process curr node
if (curr.data <= prevValue) {
// Not in ascending order
return false;
}
prevValue = curr.data;
curr = curr.right;
} else {
// Find the inorder predecessor of curr
pre = curr.left;
while (pre.right != null && pre.right != curr) {
pre = pre.right;
}
if (pre.right == null) {
// Create a temporary thread to the curr node
pre.right = curr;
curr = curr.left;
} else {
// Remove the temporary thread
pre.right = null;
// Process the curr node
if (curr.data <= prevValue) {
// Not in ascending order
return false;
}
prevValue = curr.data;
curr = curr.right;
}
}
}
return true;
}
//Driver Code Starts
static void Main() {
// Create a sample binary tree
// 10
// / \
// 5 20
// / \
// 9 25
Node root = new Node(10);
root.left = new Node(5);
root.right = new Node(20);
root.right.left = new Node(9);
root.right.right = new Node(25);
if (isBST(root)) {
Console.WriteLine("True");
}
else {
Console.WriteLine("False");
}
}
}
//Driver Code Ends
JavaScript
//Driver Code Starts
// JavaScript program to check if a tree is BST
// using Morris Traversal
class Node {
constructor(value) {
this.data = value;
this.left = null;
this.right = null;
}
}
//Driver Code Ends
// Function to check if the binary tree is a
// BST using Morris Traversal
function isBST(root) {
let curr = root;
let prevValue = -Infinity;
while (curr !== null) {
if (curr.left === null) {
// Process curr node
if (curr.data <= prevValue) {
// Not in ascending order
return false;
}
prevValue = curr.data;
curr = curr.right;
} else {
// Find the inorder predecessor of curr
let pre = curr.left;
while (pre.right !== null && pre.right !== curr) {
pre = pre.right;
}
if (pre.right === null) {
// Create a temporary thread to the curr node
pre.right = curr;
curr = curr.left;
} else {
// Remove the temporary thread
pre.right = null;
// Process the curr node
if (curr.data <= prevValue) {
// Not in ascending order
return false;
}
prevValue = curr.data;
curr = curr.right;
}
}
}
return true;
}
//Driver Code Starts
// Driver Code
// Create a sample binary tree
// 10
// / \
// 5 20
// / \
// 9 25
const root = new Node(10);
root.left = new Node(5);
root.right = new Node(20);
root.right.left = new Node(9);
root.right.right = new Node(25);
if (isBST(root)) {
console.log("True");
} else {
console.log("False");
}
//Driver Code Ends
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem