VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-given-sorted-sub-sequence-exists-in-binary-search-tree/

⇱ Check if given sorted sub-sequence exists in binary search tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if given sorted sub-sequence exists in binary search tree

Last Updated : 23 Jul, 2025

Given a binary search tree and a sorted sub-sequence, the task is to check if the given sorted sub-sequence exists in the binary search tree or not.

Examples:

Input: seq[] = {4, 6, 8, 14}

👁 Check-if-given-sorted-sub-sequence-exists-in-binary-search-tree

Output: True

Input: seq[] = {4, 6, 8, 12, 13}

👁 Check-if-given-sorted-sub-sequence-exists-in-binary-search-tree

Output: False

A simple solution is to store inorder traversal in an auxiliary array and then by matching elements of sorted sub-sequence one by one with inorder traversal of tree , we can if sub-sequence exist in BST or not. Time complexity for this approach will be O(n) but it requires extra space O(n) for storing traversal in an array.

[Naive Approach] Using In-order traversal - O(n) Time and O(h) Space

An efficient solution is to match elements of sub-sequence while we are traversing BST in inorder fashion. We take index as a iterator for given sorted sub-sequence and start inorder traversal of given bst, if current node matches with seq[index] then move index in forward direction by incrementing 1 and after complete traversal of BST if index==n that means all elements of given sub-sequence have been matched and exist as a sorted sub-sequence in given BST. 

Below is the implementation of the above approach: 


Output
True

[Alternate Approach] Using Morris Traversal Algorithm - O(n) Time and O(1) Space

The idea is to use Morris Traversal Algorithm to perform in-order traversal. At each node, if the value of node is equal to value at current index. Then increment the index. Then, if the index is equal to size of array, then return true. Else return false.

Below is the implementation of the above approach:


Output
True
Comment
Article Tags: