Check if given sorted sub-sequence exists in binary search tree
Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
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}
Output: True
Input: seq[] = {4, 6, 8, 12, 13}
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:
C++
// C++ program to find if given array exists as a// subsequence in BST#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function to traverse the tree in in-order traversal and // compare the values of sequence and tree/voidinOrder(Node*root,vector<int>seq,int&index){if(root==nullptr)return;// We traverse left subtree first in InorderinOrder(root->left,seq,index);// If current node matches with se[index] then move// forward in sub-sequenceif(index<seq.size()&&root->data==seq[index])index++;// We traverse left subtree in the end in InorderinOrder(root->right,seq,index);}boolseqExist(Node*root,vector<int>seq){// Initialize index in seq[]intindex=0;// Do an inorder traversal and find if all// elements of seq[] were presentinOrder(root,seq,index);// index would become n if all elements of// seq[] were presentreturn(index==seq.size());}intmain(){// Structure of BST// 8// / \ // 3 10// / \ \ // 1 6 14// / \ /// 4 7 13Node*root=newNode(8);root->left=newNode(3);root->right=newNode(10);root->left->left=newNode(1);root->left->right=newNode(6);root->left->right->left=newNode(4);root->left->right->right=newNode(7);root->right->right=newNode(14);root->right->right->left=newNode(13);vector<int>seq={4,6,8,14};if(seqExist(root,seq)){cout<<"True";}else{cout<<"False";}return0;}
Java
// Java program to find if given array exists as a// subsequence in BSTimportjava.util.ArrayList;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Function to traverse the tree in in-order traversal and // compare the values of sequence and treestaticvoidinOrder(Noderoot,ArrayList<Integer>seq,int[]index){if(root==null)return;// We traverse left subtree first in InorderinOrder(root.left,seq,index);// If current node matches with seq[index] then move// forward in sub-sequenceif(index[0]<seq.size()&&root.data==seq.get(index[0]))index[0]++;// We traverse right subtree in the end in InorderinOrder(root.right,seq,index);}staticbooleanseqExist(Noderoot,ArrayList<Integer>seq){// Initialize index in seq[]int[]index={0};// Do an inorder traversal and find if all// elements of seq[] were presentinOrder(root,seq,index);// index would become seq.size() if all elements of// seq[] were presentreturn(index[0]==seq.size());}publicstaticvoidmain(String[]args){// Structure of BST// 8// / \// 3 10// / \ \// 1 6 14// / \ /// 4 7 13Noderoot=newNode(8);root.left=newNode(3);root.right=newNode(10);root.left.left=newNode(1);root.left.right=newNode(6);root.left.right.left=newNode(4);root.left.right.right=newNode(7);root.right.right=newNode(14);root.right.right.left=newNode(13);ArrayList<Integer>seq=newArrayList<>();seq.add(4);seq.add(6);seq.add(8);seq.add(14);if(seqExist(root,seq)){System.out.println("True");}else{System.out.println("False");}}}
Python
# Python program to find if given array exists as a# subsequence in BSTclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to traverse the tree in in-order traversal and # compare the values of sequence and treedefinOrder(root,seq,index):ifrootisNone:return# We traverse left subtree first in InorderinOrder(root.left,seq,index)# If current node matches with seq[index] then move# forward in sub-sequenceifindex[0]<len(seq)androot.data==seq[index[0]]:index[0]+=1# We traverse right subtree in the end in InorderinOrder(root.right,seq,index)defseqExist(root,seq):# Initialize index in seq[]index=[0]# Do an inorder traversal and find if all# elements of seq[] were presentinOrder(root,seq,index)# index would become len(seq) if all elements of# seq[] were presentreturnindex[0]==len(seq)if__name__=="__main__":# Structure of BST# 8# / \# 3 10# / \ \# 1 6 14# / \ /# 4 7 13root=Node(8)root.left=Node(3)root.right=Node(10)root.left.left=Node(1)root.left.right=Node(6)root.left.right.left=Node(4)root.left.right.right=Node(7)root.right.right=Node(14)root.right.right.left=Node(13)seq=[4,6,8,14]ifseqExist(root,seq):print("True")else:print("False")
C#
// C# program to find if given array exists as a// subsequence in BSTusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Function to traverse the tree in in-order traversal and // compare the values of sequence and treestaticvoidinOrder(Noderoot,List<int>seq,refintindex){if(root==null)return;// We traverse left subtree first in InorderinOrder(root.left,seq,refindex);// If current node matches with seq[index] then move// forward in sub-sequenceif(index<seq.Count&&root.data==seq[index])index++;// We traverse right subtree in the end in InorderinOrder(root.right,seq,refindex);}staticboolseqExist(Noderoot,List<int>seq){// Initialize index in seq[]intindex=0;// Do an inorder traversal and find if all// elements of seq[] were presentinOrder(root,seq,refindex);// index would become seq.Count if all elements of// seq[] were presentreturnindex==seq.Count;}staticvoidMain(string[]args){// Structure of BST// 8// / \// 3 10// / \ \// 1 6 14// / \ /// 4 7 13Noderoot=newNode(8);root.left=newNode(3);root.right=newNode(10);root.left.left=newNode(1);root.left.right=newNode(6);root.left.right.left=newNode(4);root.left.right.right=newNode(7);root.right.right=newNode(14);root.right.right.left=newNode(13);List<int>seq=newList<int>{4,6,8,14};if(seqExist(root,seq)){Console.WriteLine("True");}else{Console.WriteLine("False");}}}
JavaScript
// JavaScript program to find if given array exists as a// subsequence in BSTclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to traverse the tree in in-order traversal and // compare the values of sequence and treefunctioninOrder(root,seq,index){if(root===null)return;// We traverse left subtree first in InorderinOrder(root.left,seq,index);// If current node matches with seq[index] then move// forward in sub-sequenceif(index[0]<seq.length&&root.data===seq[index[0]]){index[0]++;}// We traverse right subtree in the end in InorderinOrder(root.right,seq,index);}functionseqExist(root,seq){// Initialize index in seq[]letindex=[0];// Do an inorder traversal and find if all// elements of seq[] were presentinOrder(root,seq,index);// index would become seq.length if all elements of// seq[] were presentreturnindex[0]===seq.length;}// Structure of BST// 8// / \// 3 10// / \ \// 1 6 14// / \ /// 4 7 13letroot=newNode(8);root.left=newNode(3);root.right=newNode(10);root.left.left=newNode(1);root.left.right=newNode(6);root.left.right.left=newNode(4);root.left.right.right=newNode(7);root.right.right=newNode(14);root.right.right.left=newNode(13);letseq=[4,6,8,14];if(seqExist(root,seq)){console.log("True");}else{console.log("False");}
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:
C++
// C++ program to find if given array exists as a// subsequence in BST#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function to perform Morris Traversal and check// if array is subsequence in BSTboolseqExist(Node*root,vector<int>seq){Node*curr=root;intindex=0;while(curr!=nullptr){// if left tree does not exists,// then compare the curr node with // current value and set curr = curr->rightif(curr->left==nullptr){if(index<seq.size()&&seq[index]==curr->data)index++;curr=curr->right;}else{Node*pred=curr->left;// find the inorder predecessor while(pred->right!=nullptr&&pred->right!=curr){pred=pred->right;}// create a linkage between pred and// curr and move to left node.if(pred->right==nullptr){pred->right=curr;curr=curr->left;}// if pred->right = curr, it means // we have processed the left subtree,// and we can compare curr nodeelse{if(index<seq.size()&&seq[index]==curr->data)index++;curr=curr->right;}}}returnindex==seq.size();}intmain(){// Structure of BST// 8// / \ // 3 10// / \ \ // 1 6 14// / \ /// 4 7 13Node*root=newNode(8);root->left=newNode(3);root->right=newNode(10);root->left->left=newNode(1);root->left->right=newNode(6);root->left->right->left=newNode(4);root->left->right->right=newNode(7);root->right->right=newNode(14);root->right->right->left=newNode(13);vector<int>seq={4,6,8,14};if(seqExist(root,seq)){cout<<"True";}else{cout<<"False";}return0;}
Java
// Java program to find if given array exists as a// subsequence in BSTimportjava.util.ArrayList;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Function to perform Morris Traversal and check// if array is subsequence in BSTstaticbooleanseqExist(Noderoot,ArrayList<Integer>seq){Nodecurr=root;intindex=0;while(curr!=null){// if left tree does not exist,// then compare the curr node with// current value and set curr = curr.rightif(curr.left==null){if(index<seq.size()&&seq.get(index)==curr.data)index++;curr=curr.right;}else{Nodepred=curr.left;// find the inorder predecessorwhile(pred.right!=null&&pred.right!=curr){pred=pred.right;}// create a linkage between pred and// curr and move to left node.if(pred.right==null){pred.right=curr;curr=curr.left;}// if pred.right = curr, it means// we have processed the left subtree,// and we can compare curr nodeelse{if(index<seq.size()&&seq.get(index)==curr.data)index++;curr=curr.right;}}}returnindex==seq.size();}publicstaticvoidmain(String[]args){// Structure of BST// 8// / \// 3 10// / \ \// 1 6 14// / \ /// 4 7 13Noderoot=newNode(8);root.left=newNode(3);root.right=newNode(10);root.left.left=newNode(1);root.left.right=newNode(6);root.left.right.left=newNode(4);root.left.right.right=newNode(7);root.right.right=newNode(14);root.right.right.left=newNode(13);ArrayList<Integer>seq=newArrayList<>();seq.add(4);seq.add(6);seq.add(8);seq.add(14);if(seqExist(root,seq)){System.out.println("True");}else{System.out.println("False");}}}
Python
# Python program to find if given array exists as a# subsequence in BSTclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to perform Morris Traversal and check# if array is subsequence in BSTdefseqExist(root,seq):curr=rootindex=0whilecurrisnotNone:# if left tree does not exist,# then compare the curr node with# current value and set curr = curr.rightifcurr.leftisNone:ifindex<len(seq)andseq[index]==curr.data:index+=1curr=curr.rightelse:pred=curr.left# find the inorder predecessorwhilepred.rightisnotNoneandpred.right!=curr:pred=pred.right# create a linkage between pred and# curr and move to left node.ifpred.rightisNone:pred.right=currcurr=curr.leftelse:# if pred.right = curr, it means# we have processed the left subtree,# and we can compare curr nodeifindex<len(seq)andseq[index]==curr.data:index+=1curr=curr.rightreturnindex==len(seq)if__name__=="__main__":# Structure of BST# 8# / \# 3 10# / \ \# 1 6 14# / \ /# 4 7 13root=Node(8)root.left=Node(3)root.right=Node(10)root.left.left=Node(1)root.left.right=Node(6)root.left.right.left=Node(4)root.left.right.right=Node(7)root.right.right=Node(14)root.right.right.left=Node(13)seq=[4,6,8,14]ifseqExist(root,seq):print("True")else:print("False")
C#
// C# program to find if given array exists as a// subsequence in BSTusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Function to perform Morris Traversal and check// if array is subsequence in BSTstaticboolseqExist(Noderoot,List<int>seq){Nodecurr=root;intindex=0;while(curr!=null){// if left tree does not exist,// then compare the curr node with// current value and set curr = curr.rightif(curr.left==null){if(index<seq.Count&&seq[index]==curr.data)index++;curr=curr.right;}else{Nodepred=curr.left;// find the inorder predecessorwhile(pred.right!=null&&pred.right!=curr){pred=pred.right;}// create a linkage between pred and// curr and move to left node.if(pred.right==null){pred.right=curr;curr=curr.left;}else{// if pred.right = curr, it means// we have processed the left subtree,// and we can compare curr nodeif(index<seq.Count&&seq[index]==curr.data)index++;curr=curr.right;}}}returnindex==seq.Count;}staticvoidMain(){// Structure of BST// 8// / \// 3 10// / \ \// 1 6 14// / \ /// 4 7 13Noderoot=newNode(8);root.left=newNode(3);root.right=newNode(10);root.left.left=newNode(1);root.left.right=newNode(6);root.left.right.left=newNode(4);root.left.right.right=newNode(7);root.right.right=newNode(14);root.right.right.left=newNode(13);List<int>seq=newList<int>{4,6,8,14};if(seqExist(root,seq)){Console.WriteLine("True");}else{Console.WriteLine("False");}}}
JavaScript
// JavaScript program to find if given array exists as a// subsequence in BSTclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to perform Morris Traversal and check// if array is subsequence in BSTfunctionseqExist(root,seq){letcurr=root;letindex=0;while(curr!==null){// if left tree does not exist,// then compare the curr node with// current value and set curr = curr.rightif(curr.left===null){if(index<seq.length&&seq[index]===curr.data)index++;curr=curr.right;}else{letpred=curr.left;// find the inorder predecessorwhile(pred.right!==null&&pred.right!==curr){pred=pred.right;}// create a linkage between pred and// curr and move to left node.if(pred.right===null){pred.right=curr;curr=curr.left;}else{// if pred.right = curr, it means// we have processed the left subtree,// and we can compare curr nodeif(index<seq.length&&seq[index]===curr.data)index++;curr=curr.right;}}}returnindex===seq.length;}// Structure of BST// 8// / \// 3 10// / \ \// 1 6 14// / \ /// 4 7 13letroot=newNode(8);root.left=newNode(3);root.right=newNode(10);root.left.left=newNode(1);root.left.right=newNode(6);root.left.right.left=newNode(4);root.left.right.right=newNode(7);root.right.right=newNode(14);root.right.right.left=newNode(13);letseq=[4,6,8,14];if(seqExist(root,seq)){console.log("True");}else{console.log("False");}