Norway


#include <iostream>

using namespace std;

 

// structure for BST node

struct Node {

    int data;

    Node *left, *right;

 

    Node(int data)

    {

        this->data = data;

        this->left = this->right = nullptr;

    }

};

 

// Recursive function to insert an into BST

Node* insert(Node* root, int key)

{

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

    if (root == nullptr)

        return new Node(key);

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

    if (key < root->data)

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

    // else recurse for right subtree

    else

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

    // return root node

    return root;

}

 

// Function to in a BST whose within a given

// It returns true if whole subtree rooted at given node is within range

bool findSubTrees(Node* root, int low, int high, int& count)

{

    // base case

    if (root == nullptr)

        return true;

 

    // increment the subtree count by 1 and return true if the root node,

    // left and right subtree are within the range

    if (findSubTrees(root->left, low, high, count) &&

        findSubTrees(root->right, low, high, count) &&

        (root->data >= low && root->data <= high))

    {

        count++;

        return true;

    }

 

    return false;

}

 

int main()

{

    // input range

    int low = 5, high = 20;

 

    // BST keys to construct BST shown in the diagram

    int keys[] = { 15, 25, 20, 22, 30, 18, , 8, 9, , 6 };

 

    // construct BST

    Node* root = nullptr;

    for (int key : keys)

        root = insert(root, key);

 

    // get subtrees count

    int count = 0;

    findSubTrees(root, low, high, count);

    cout << “The number of subtrees are: “ << count;

 

    return 0;

}



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here