Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Check if a Binary Tree is BST or not
Next article icon

Check if a Binary Tree is BST or not

Last Updated : 17 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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.

Table of Content

  • [Approach - 1] Using specified range of Min and Max Values - O(n) Time and O(h) Space
  • [Approach - 2] Using Inorder Traversal - O(n) Time and O(h) Space
  • [Approach - 3] Using Morris Traversal - O(n) Time and O(1) Space

[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 

Output
False 

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 

Output
False 

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 

Output
False 



Next Article
Check if a Binary Tree is BST or not

K

kartik
Improve
Article Tags :
  • Tree
  • Binary Search Tree
  • DSA
  • Microsoft
  • Amazon
  • Adobe
  • Qualcomm
  • Walmart
  • VMWare
  • Snapdeal
  • Accolite
  • MakeMyTrip
  • FactSet
  • OYO
  • Boomerang Commerce
  • GreyOrange
  • Wooker
Practice Tags :
  • Accolite
  • Adobe
  • Amazon
  • Boomerang Commerce
  • FactSet
  • GreyOrange
  • MakeMyTrip
  • Microsoft
  • Qualcomm
  • Snapdeal
  • VMWare
  • Walmart
  • Wooker
  • Binary Search Tree
  • Tree

Similar Reads

    Binary Search Tree
    A Binary Search Tree (BST) is a type of binary tree data structure in which each node contains a unique key and satisfies a specific ordering property:All nodes in the left subtree of a node contain values strictly less than the node’s value. All nodes in the right subtree of a node contain values s
    4 min read
    Introduction to Binary Search Tree
    Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and for every nodes, its left subtree contains values less than the node and the right subtree contains values greater than the
    3 min read
    Applications of BST
    Binary Search Tree (BST) is a data structure that is commonly used to implement efficient searching, insertion, and deletion operations along with maintaining sorted sequence of data. Please remember the following properties of BSTs before moving forward.The left subtree of a node contains only node
    3 min read
    Applications, Advantages and Disadvantages of Binary Search Tree
    A Binary Search Tree (BST) is a data structure used to storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the p
    2 min read
    Insertion in Binary Search Tree (BST)
    Given a BST, the task is to insert a new node in this BST.Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is fo
    15 min read
    Searching in Binary Search Tree (BST)
    Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInp
    7 min read
    Deletion in Binary Search Tree (BST)
    Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios:Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BSTDeleting a single child node is also simple in BST. Copy the child to the node and delete the node. Case 3. Delete a Node w
    10 min read
    Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
    Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree. Input: A Binary Search TreeOutput: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 1
    10 min read
    Balance a Binary Search Tree
    Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height.Examples: Input: Output: Explanation: The above unbalanced BST is converted to balanced with the minimum possible height.Input: Output: Explanation: The above u
    10 min read
    Self-Balancing Binary Search Trees
    Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences