VOOZH about

URL: https://www.geeksforgeeks.org/dsa/iterative-approach-to-check-if-a-binary-tree-is-bst-or-not/

⇱ Iterative approach to check if a Binary Tree is BST or not - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Iterative approach to check if a Binary Tree is BST or not

Last Updated : 23 Jul, 2025

Given a Binary Tree, the task is to check if the given binary tree is a Binary Search Tree or not. If found to be true, then print "YES". Otherwise, print "NO".

Examples:

Input: 

 9
 / \
 6 10
 / \ \
 4 7 11
 / \ \
 3 5 8

Output: YES 
Explanation: Since the left subtree of each node of the tree consists of smaller valued nodes and the right subtree of each node of the tree consists of larger valued nodes. Therefore, the required is output is "YES".

Input:  

 5
 / \
 6 3
 / \ \
 4 9 2

Output: NO 
 

Recursive Approach: Refer to the previous post to solve this problem using recursion. 
Time Complexity: O(N) where N is the count of nodes in the Binary Tree. 
Auxiliary Space: O(N)

Iterative Approach: To solve the problem iteratively, use Stack. Follow the steps below to solve the problem:

Below is the implementation of the above approach.


Output: 
YES

 

Time Complexity: O(N), where N is count of nodes in the binary tree 
Auxiliary Space: O(N)

Comment