
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Find postorder traversal of BST from preorder traversal in C++
- Construct BST from given preorder traversal - Set 1 in C++
- Construct BST from given preorder traversal - Set 2 in C++
- Find Number of Array Elements Smaller than a Given Number in Java
- Recover a Tree From Preorder Traversal in C++
- Preorder Traversal of N-ary Tree Without Recursion in C++
- N-ary Tree Preorder Traversal in C++
- Find n-th node in Preorder traversal of a Binary Tree in C++
- C++ Program to Perform Preorder Recursive Traversal of a Given Binary Tree
- Preorder Tree Traversal in Data Structures
- Binary Tree Preorder Traversal in Python
- C++ Program to Perform Preorder Non-Recursive Traversal of a Given Binary Tree
- Construct a BST from given postorder traversal using Stack in Python
- Check if a given array can represent Preorder Traversal of Binary Search Tree in C++
- Program to generate tree using preorder and inorder traversal in python

Advertisements