Number of elements smaller than root using preorder traversal of a BST in C++


You are given the result of the preorder traversal. You need to find the number of elements that are smaller than the root.

The first element in the preorder traversal is the root of the BST. Let's see an example.

Input

preorder_result = [5, 4, 2, 1, 7, 6, 8, 9]

Output

3

There are three elements that are less than the root. The root is 5.

Algorithm

  • Initialise the preorder result in an array.

  • Store the first element i.e.., root of the BST in a variable.

  • Write a loop that iterates from the 2nd element of the preorder result.

    • Compare every element with the root.

    • If the current element is greater than the root, then increment the count.

  • Return the count.

Implementation

Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>
using namespace std;
int getElementsCount(int arr[], int n) {
   if (n < 0) {
      return 0;
   }
   int i, root = arr[0], count = 0;
   for(i = 1; i < n; i++) {
      if(arr[i] < root) {
         count += 1;
      }
   }
   return count;
}
int main() {
   int preorder[] = {5, 4, 2, 1, 7, 6, 8, 9};
   int n = 8;
   cout << getElementsCount(preorder, n) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

3

Updated on: 26-Oct-2021

53 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements