Check if a Binary Tree is BST or not
Last Updated :
25 Sep, 2024
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.
[Naive Approach] – O(n^2) Time and O(n) Space:
The idea is to check for each node, if the maximum value in the left subtree is smaller than the node and if the minimum value in the right subtree is greater than the node. By recursively applying this validation across all nodes, we can confirm whether the tree satisfies the properties of a BST.
Below is the implementation of the above approach:
C++
// C++ program to check if a tree is BST
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = right = nullptr;
}
};
// Function to find max value in the subtree
int maxValue(Node* node) {
if (node == nullptr)
return INT_MIN;
return max({node->data,
maxValue(node->left),
maxValue(node->right)});
}
// Function to find min value in the subtree
int minValue(Node* node) {
if (node == nullptr)
return INT_MAX;
return min({node->data,
minValue(node->left),
minValue(node->right)});
}
// Returns true if the binary tree is a BST
bool isBST(Node* node) {
if (node == nullptr)
return true;
// Check if the max of the left subtree
// is greater than current node
if (node->left != nullptr && maxValue(node->left) >= node->data)
return false;
// Check if the min of the right subtree
// is smaller than or equal to current node
if (node->right != nullptr && minValue(node->right) <= node->data)
return false;
// Recursively check if left and right subtrees are BSTs
return isBST(node->left) && isBST(node->right);
}
int main() {
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
Node* root = new Node(4);
root->left = new Node(2);
root->right = new Node(5);
root->left->left = new Node(1);
root->left->right = new Node(3);
if (isBST(root)) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
return 0;
}
C
// C program to check if a tree is BST
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to find max value in the subtree
int maxValue(struct Node* node) {
if (node == NULL)
return INT_MIN;
int leftMax = maxValue(node->left);
int rightMax = maxValue(node->right);
return (node->data > leftMax && node->data > rightMax) ?
node->data : (leftMax > rightMax ? leftMax : rightMax);
}
// Function to find min value in the subtree
int minValue(struct Node* node) {
if (node == NULL)
return INT_MAX;
int leftMin = minValue(node->left);
int rightMin = minValue(node->right);
return (node->data < leftMin && node->data < rightMin) ?
node->data : (leftMin < rightMin ? leftMin : rightMin);
}
// Returns true if the binary tree is a BST
int isBST(struct Node* node) {
if (node == NULL)
return 1;
// Check if the max of the left subtree
// is greater than current node
if (node->left != NULL && maxValue(node->left) >= node->data)
return 0;
// Check if the min of the right subtree
// is smaller than or equal to current node
if (node->right != NULL && minValue(node->right) <= node->data)
return 0;
// Recursively check if left and right subtrees are BSTs
return isBST(node->left) && isBST(node->right);
}
struct Node* createNode(int value) {
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->data = value;
node->left = node->right = NULL;
return node;
}
int main() {
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
struct Node* root = createNode(4);
root->left = createNode(2);
root->right = createNode(5);
root->left->left = createNode(1);
root->left->right = createNode(3);
if (isBST(root)) {
printf("True");
}
else {
printf("False");
}
return 0;
}
Java
// Java program to check if a tree is BST
class Node {
int data;
Node left, right;
Node(int value) {
data = value;
left = right = null;
}
}
class GfG {
// Function to find max value in the subtree
static int maxValue(Node node) {
if (node == null) return Integer.MIN_VALUE;
return
Math.max(node.data,
Math.max(maxValue(node.left), maxValue(node.right)));
}
// Function to find min value in the subtree
static int minValue(Node node) {
if (node == null) return Integer.MAX_VALUE;
return
Math.min(node.data,
Math.min(minValue(node.left), minValue(node.right)));
}
// Returns true if the binary tree is a BST
static boolean isBST(Node node) {
if (node == null) return true;
// Check if the max of the left subtree
// is greater than current node
if (node.left != null && maxValue(node.left) >= node.data)
return false;
// Check if the min of the right subtree
// is smaller than or equal to current node
if (node.right != null && minValue(node.right) <= node.data)
return false;
// Recursively check if left and right subtrees are BSTs
return isBST(node.left) && isBST(node.right);
}
public static void main(String[] args) {
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(3);
if (isBST(root)) {
System.out.println("True");
}
else {
System.out.println("False");
}
}
}
Python
# Python program to check if a tree is BST
class Node:
def __init__(self, value):
self.data = value
self.left = None
self.right = None
# Function to find max value in the subtree
def maxValue(node):
if node is None:
return float('-inf')
return max(node.data, maxValue(node.left), maxValue(node.right))
# Function to find min value in the subtree
def minValue(node):
if node is None:
return float('inf')
return min(node.data, minValue(node.left), minValue(node.right))
# Returns true if the binary tree is a BST
def isBST(node):
if node is None:
return True
# Check if the max of the left subtree is greater than current node
if node.left and maxValue(node.left) >= node.data:
return False
# Check if the min of the right subtree is smaller than
# or equal to current node
if node.right and minValue(node.right) <= node.data:
return False
# Recursively check if left and right subtrees are BSTs
return isBST(node.left) and isBST(node.right)
if __name__ == "__main__":
# Create a sample binary tree
# 4
# / \
# 2 5
# / \
# 1 3
root = Node(4)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(1)
root.left.right = Node(3)
if isBST(root):
print("True")
else:
print("False")
C#
// C# program to check if a tree is BST
using System;
public class Node {
public int data;
public Node left, right;
public Node(int value) {
data = value;
left = right = null;
}
}
class GfG {
// Function to find max value in the subtree
static int MaxValue(Node node) {
if (node == null) return Int32.MinValue;
return
Math.Max(node.data,
Math.Max(MaxValue(node.left), MaxValue(node.right)));
}
// Function to find min value in the subtree
static int MinValue(Node node) {
if (node == null) return Int32.MaxValue;
return
Math.Min(node.data,
Math.Min(MinValue(node.left), MinValue(node.right)));
}
// Returns true if the binary tree is a BST
static bool isBST(Node node) {
if (node == null) return true;
// Check if the max of the left subtree
// is greater than current node
if (node.left != null && MaxValue(node.left) >= node.data)
return false;
// Check if the min of the right subtree
// is smaller than or equal to current node
if (node.right != null && MinValue(node.right) <= node.data)
return false;
// Recursively check if left and right subtrees are BSTs
return isBST(node.left) && isBST(node.right);
}
static void Main() {
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(3);
if (isBST(root)) {
Console.WriteLine("True");
}
else {
Console.WriteLine("False");
}
}
}
JavaScript
// JavaScript program to check if a tree is BST
// Node class
class Node {
constructor(value) {
this.data = value;
this.left = null;
this.right = null;
}
}
// Function to find max value in the subtree
function maxValue(node) {
if (node === null) return -Infinity;
return
Math.max(node.data,
maxValue(node.left), maxValue(node.right));
}
// Function to find min value in the subtree
function minValue(node) {
if (node === null) return Infinity;
return
Math.min(node.data,
minValue(node.left), minValue(node.right));
}
// Returns true if the binary tree is a BST
function isBST(node) {
if (node === null) return true;
// Check if the max of the left subtree
// is greater than current node
if (node.left !== null && maxValue(node.left) >= node.data)
return false;
// Check if the min of the right subtree
// is smaller than or equal to current node
if (node.right !== null && minValue(node.right) <= node.data)
return false;
// Recursively check if left and right subtrees are BSTs
return isBST(node.left) && isBST(node.right);
}
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
const root = new Node(4);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(3);
if (isBST(root)) {
console.log("True");
} else {
console.log("False");
}
Note: It is assumed that you have helper functions minValue() and maxValue() that return the min or max int value from a non-empty tree
Time Complexity: O(n2), As we visit every node just once and our helper method also takes O(n) time, so overall time complexity is O(n2)
Auxiliary Space: O(h), Where h is the height of the binary tree.
[Better 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.
Below is the illustration of above approach:
Below is the implementation of the above approach:
C++
// C++ program to check if a tree is BST
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = right = nullptr;
}
};
// 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);
}
int main() {
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
Node* root = new Node(4);
root->left = new Node(2);
root->right = new Node(5);
root->left->left = new Node(1);
root->left->right = new Node(3);
if (isBST(root)) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
return 0;
}
C
// C program to check if a tree is BST
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// 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);
}
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
// 4
// / \
// 2 5
// / \
// 1 3
struct Node* root = createNode(4);
root->left = createNode(2);
root->right = createNode(5);
root->left->left = createNode(1);
root->left->right = createNode(3);
if (isBST(root)) {
printf("True");
}
else {
printf("False");
}
return 0;
}
Java
// Java program to check if a tree is BST
class Node {
int data;
Node left, right;
Node(int value) {
data = value;
left = right = null;
}
}
class GfG {
// 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);
}
public static void main(String[] args) {
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(3);
if (isBST(root)) {
System.out.println("True");
}
else {
System.out.println("False");
}
}
}
Python
class Node:
def __init__(self, value):
self.data = value
self.left = None
self.right = None
# 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'))
if __name__ == "__main__":
# Create a sample binary tree
# 4
# / \
# 2 5
# / \
# 1 3
root = Node(4)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(1)
root.left.right = Node(3)
if isBST(root):
print("True")
else:
print("False")
C#
// C# program to check if a tree is BST
using System;
class Node {
public int data;
public Node left, right;
public Node(int value) {
data = value;
left = right = null;
}
}
class GfG {
// 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);
}
static void Main() {
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(3);
if (isBST(root)) {
Console.WriteLine("True");
}
else {
Console.WriteLine("False");
}
}
}
JavaScript
// JavaScript program to check if a tree is BST
class Node {
constructor(value) {
this.data = value;
this.left = this.right = null;
}
}
// 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);
}
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
const root = new Node(4);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(3);
if (isBST(root)) {
console.log("True");
} else {
console.log("False");
}
Time Complexity: O(n), where n is the number of nodes in the tree.
Auxiliary Space: O(h), where h is the height of the tree.
[Better Approach – 2] Using Inorder Traversal – O(n) Time and O(h) Space:
The idea is to use inorder traversal of a binary search tree, which generates output sorted in ascending order. After generating the inorder traversal of the given binary tree, we can check if the values are sorted or not.
Follow the below steps to solve the problem:
- Perform an inorder traversal of the tree.
- Store the values from the traversal in an array.
- Check if the values in the array or list are sorted in ascending order. If they are, then the tree is a BST.
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.
Below is the implementation of the above approach:
C++
//C++ program to check if a tree is
// BST using Inorder Traversal
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = right = nullptr;
}
};
// Function to check if the tree is a valid BST
bool isValidBST(Node* root, int &prev) {
if (!root) return true;
// Recursively check the left subtree
if (!isValidBST(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 isValidBST(root->right, prev);
}
// Wrapper function to initialize previous value
// and call the recursive function
bool isBST(Node* root) {
int prev = INT_MIN;
return isValidBST(root, prev);
}
int main() {
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
Node* root = new Node(4);
root->left = new Node(2);
root->right = new Node(5);
root->left->left = new Node(1);
root->left->right = new Node(3);
if(isBST(root)) {
cout << "True";
}
else cout << "False";
return 0;
}
C
#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;
};
// Function to check if the tree is a valid BST
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);
}
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
// 4
// / \
// 2 5
// / \
// 1 3
struct Node* root = createNode(4);
root->left = createNode(2);
root->right = createNode(5);
root->left->left = createNode(1);
root->left->right = createNode(3);
if (isBST(root)) {
printf("True\n");
} else {
printf("False\n");
}
return 0;
}
Java
//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 {
// Function to check if the tree is a valid BST
static boolean isValidBST(Node root, int[] prev) {
if (root == null) return true;
// Check the left subtree
if (!isValidBST(root.left, prev)) return false;
// Check current node value against previous value
if (prev[0] >= root.data) return false;
// Update previous value to current node's value
prev[0] = root.data;
// Check the right subtree
return isValidBST(root.right, prev);
}
// Wrapper function to call the recursive function
static boolean isBST(Node root) {
// we need to make one size array to hold previous value
int[] prev = {Integer.MIN_VALUE};
return isValidBST(root, prev);
}
public static void main(String[] args) {
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(3);
if (isBST(root)) {
System.out.println("True");
}
else {
System.out.println("False");
}
}
}
Python
class Node:
def __init__(self, value):
self.data = value
self.left = None
self.right = None
def isValidBst(node, prev):
if node is None:
return True
# Check the left subtree
if not isValidBst(node.left, prev):
return False
# Check current node value against the previous node's value
if prev[0] is not None and prev[0] >= node.data:
return False
# Update the previous node's value
prev[0] = node.data
# Check the right subtree
return isValidBst(node.right, prev)
def isBST(root):
# Using a list to simulate pass-by-reference
prev = [None]
return isValidBst(root, prev)
if __name__ == '__main__':
# Create a sample binary tree
# 4
# / \
# 2 5
# / \
# 1 3
root = Node(4)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(1)
root.left.right = Node(3)
if isBST(root):
print("True")
else:
print("False")
C#
//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 {
// Function to check if the tree is a valid BST
static bool IsValidBST(Node node, ref int prev) {
if (node == null) return true;
// Check the left subtree
if (!IsValidBST(node.left, ref prev)) {
return false;
}
// Check the current node's value
if (prev >= node.Data) {
return false;
}
// Update the previous value
prev = node.Data;
// Check the right subtree
return IsValidBST(node.right, ref prev);
}
// Wrapper function for IsValidBST
static bool isBST(Node root) {
int prev = int.MinValue;
return IsValidBST(root, ref prev);
}
static void Main() {
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(3);
if (isBST(root)) {
Console.WriteLine("True");
}
else {
Console.WriteLine("False");
}
}
}
JavaScript
//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;
}
}
// Function to check if the tree is a valid BST
function isValidBST(node, prev) {
if (node === null)
return true;
// Recursively check the left subtree
if (!isValidBST(node.left, prev))
return false;
// Check the current node value against the previous
// value
if (prev.value !== null && prev.value >= node.data)
return false;
// Update the previous value to the current node's value
prev.value = node.data;
// Recursively check the right subtree
return isValidBST(node.right, prev);
}
// Wrapper function to initialize previous value
// and call the recursive function
function isBST(root) {
const prev = {value : null};
return isValidBST(root, prev);
}
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
let root = new Node(4);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(3);
if (isBST(root)) {
console.log("True");
} else {
console.log("False");
}
Time Complexity: O(n), where n is the number of nodes in the tree
Auxiliary Space: O(h), where h is the height of the tree.
[Expected Approach] 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.
Below is the implementation of the above approach:
C++
// C++ program to check if a tree is
// BST using Morris Traversal
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = right = nullptr;
}
};
// 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;
}
int main() {
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
Node* root = new Node(4);
root->left = new Node(2);
root->right = new Node(5);
root->left->left = new Node(1);
root->left->right = new Node(3);
if (isBST(root)) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
return 0;
}
C
// 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;
};
// 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;
}
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
// 4
// / \
// 2 5
// / \
// 1 3
struct Node* root = createNode(4);
root->left = createNode(2);
root->right = createNode(5);
root->left->left = createNode(1);
root->left->right = createNode(3);
if (isBST(root)) {
printf("True");
}
else {
printf("False");
}
return 0;
}
Java
// 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 {
// 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;
}
public static void main(String[] args) {
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(3);
if (isBST(root)) {
System.out.println("True");
}
else {
System.out.println("False");
}
}
}
Python
# 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
# 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
if __name__ == "__main__":
# Create a sample binary tree
# 4
# / \
# 2 5
# / \
# 1 3
root = Node(4)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(1)
root.left.right = Node(3)
if isBST(root):
print("True")
else:
print("False")
C#
// 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 {
// Function to check if the binary tree is a BST
// using Morris Traversal
public 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;
}
static void Main() {
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(3);
if (isBST(root)) {
Console.WriteLine("True");
}
else {
Console.WriteLine("False");
}
}
}
JavaScript
// 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;
}
}
// 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;
}
// Create a sample binary tree
// 4
// / \
// 2 5
// / \
// 1 3
const root = new Node(4);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(3);
if (isBST(root)) {
console.log("True");
} else {
console.log("False");
}
Time Complexity: O(n), where n is the number of nodes in the tree.
Auxiliary Space: O(1)