#include <iostream>

#include <vector>

#include <climits>

using namespace std;


// structure to store a Binary Tree node

struct Node {

    int data;

    Node *left, *right;



// Function to create a new binary tree node having given key

Node* newNode(int key)


    Node* node = new Node;

    node->data = key;

    node->left = node->right = nullptr;


    return node;



// Recursive function to insert an key into

Node* insert(Node* root, int key)


    // if the root is null, create a new node an return it

    if (root == nullptr)

        return newNode(key);


    // if given key is less than the root node, recurse for left subtree

    if (key < root->data)

        root->left = insert(root->left, key);


    // if given key is more than the root node, recurse for right subtree


        root->right = insert(root->right, key);


    return root;



// Recursive function to build a BST from given

Node* buildTree(vector<int> const &seq)


    Node* root = nullptr;


    // construct a BST by inserting keys from the given sequence

    for (int key: seq)

        root = insert(root, key);


    // return root node

    return root;



// Function to compare the of a BST with given sequence

bool comparePreOrder(Node* root, vector<int> const &seq, int &index)


    // base case

    if (root == nullptr)

        return true;


    // return false if next element in the given sequence doesn’t match

    // with the next element in preorder traversal of BST

    if (seq[index] != root->data)

        return false;


    // increment index



    // compare the left and right subtrees

    return comparePreOrder(root->left, seq, index) &&

           comparePreOrder(root->right, seq, index);



// Function to if a given sequence preorder traversal of a BST

bool isBST(vector<int> const &seq)


    /* 1. Construct the BST from given sequence */


    Node* root = buildTree(seq);


    /* 2. Compare the preorder traversal of BST with given sequence */


    // index stores index of next unprocessed node in preorder sequence

    int index = 0;

    return comparePreOrder(root, seq, index) && index == seq.size();



// main function

int main()


    vector<int> seq = { 1, , 8, 12, 20, 16, 25 };


    if (isBST(seq))

        cout << “Given sequence represents preorder traversal of a BST”;


        cout << “Given sequence doesn’t represent preorder traversal of a BST”;


    return 0;


Source link


Please enter your comment!
Please enter your name here