How to Read Binary Search Tree from File in C++?
Last Updated :
17 Jun, 2024
A binary search tree is a hierarchical data structure in which for every node in the tree, the value of all nodes in the left subtree is less than the node's value and the value of all nodes in the right subtree is greater than the node's value. This property of the binary search tree makes it efficient for searching, insertion, and deletion operations. In this article, we will learn how to read files into a binary search tree using C++.
Read Data into a Binary Search Tree From a File
To create a binary search tree using the data present in a text file, we can follow the below approach:
Approach
- Use ifstream to open the text file.
- Check if the file is successfully opened. If not print an error message and exit the function.
- Initialize an integer variable value to store the data from the file.
- Use a loop to read integers from the file.
- Inside the loop call the insert method to insert each integer into the Binary Search Tree.
- Close the file after the creation of the Binary Search Tree is complete.
Note: In this program, we create the tree on the basis of key values that are integers. You can take any type of value as a key.
C++ Program to Read Binary Search Tree from File
Let us consider a text file named abc.txt that contains the following data 30 40 50 60 10 20.
C++
// C++ Program to read a file into a binary search tree
#include <fstream>
#include <iostream>
#include <queue>
using namespace std;
// Node class for BST nodes
class Node {
public:
int data;
Node* left;
Node* right;
// Constructor to initialize node with data
Node(int data)
{
this->data = data;
this->left = nullptr;
this->right = nullptr;
}
};
// BST class for Binary Search Tree operations
class BST {
private:
// Root node of the BST
Node* root;
// Function to insert a value into the BST
Node* insertNode(Node* root, int value)
{
if (root == nullptr) {
return new Node(value);
}
if (value < root->data) {
root->left = insertNode(root->left, value);
}
else if (value > root->data) {
root->right = insertNode(root->right, value);
}
return root;
}
// Function to perform inorder traversal
void inorderTraversal(Node* root)
{
if (root == nullptr) {
return;
}
inorderTraversal(root->left);
cout << root->data << " ";
inorderTraversal(root->right);
}
// Function to search a value in the BST recursively
bool search(Node* root, int value)
{
if (root == nullptr) {
return false;
}
if (root->data == value) {
return true;
}
else if (value < root->data) {
return search(root->left, value);
}
else {
return search(root->right, value);
}
}
// Function to perform level order traversal
void printLevelOrder(Node* root)
{
if (root == nullptr) {
return;
}
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int levelSize = q.size();
for (int i = 0; i < levelSize; ++i) {
Node* current = q.front();
q.pop();
cout << current->data << " ";
if (current->left != nullptr) {
q.push(current->left);
}
if (current->right != nullptr) {
q.push(current->right);
}
}
cout << endl;
}
}
public:
// Constructor to initialize an empty BST
BST()
: root(nullptr)
{
}
// Public function to insert a value into the BST
void insert(int value)
{
root = insertNode(root, value);
}
// Public function to perform inorder traversal of the
// BST
void inorderTraversal()
{
inorderTraversal(root);
cout << endl;
}
// Public function to search for a value in the BST
bool search(int value) { return search(root, value); }
// Public function to perform level order traversal of
// the BST
void levelOrderTraversal() { printLevelOrder(root); }
/* _____Function to construct a BST from values read
* from a file _____ */
void constructFromFile(const string& filename)
{
ifstream file(filename);
if (!file.is_open()) {
cerr << "Error opening file: " << filename
<< endl;
return;
}
int value;
while (file >> value) {
// insert the values into the BST
insert(value);
}
file.close();
}
};
int main()
{
// Create an instance of BST
BST bst;
// File containing input values for BST
string filename = "abc.txt";
// Construct BST from file
bst.constructFromFile(filename);
// Perform operations on the BST
cout << "Inorder traversal of the constructed BST: "
<< endl;
bst.inorderTraversal();
cout << "Level order traversal of the BST :" << endl;
bst.levelOrderTraversal();
cout << "Search for 40 in the BST: "
<< (bst.search(40) ? "Found" : "Not found")
<< endl;
return 0;
}
Output
Inorder traversal of the constructed BST:
10 20 30 40 50 60
Level order traversal of the BST :
30
10 40
20 50
60
Search for 40 in the BST: Found
Time Complexity: O(NlogN) for constructing binary tree.
Auxiliary Space: O(N), where N is the number of nodes.
Similar Reads
How to Read From a File in C++? Reading from a file means retrieving the data stored inside a file. C++ file handling allows us to read different files from our C programs. This data can be taken as input and stored in the program for processing. Generally, files can be classified in two types:Text File: Files that contains data i
4 min read
Floor in Binary Search Tree (BST) Given a Binary Search Tree and a number x, the task is to find the floor of x in the given BST, where floor means the greatest value node of the BST which is smaller than or equal to x. if x is smaller than the smallest node of BST then return -1.Examples:Input: Output: 55Explanantion: Table of Cont
14 min read
Binary Search Tree in C++ A Binary Search Tree (BST) is a type of binary tree in which the data is organized and stored in a sorted order. Unlike, a binary tree that doesn't follow a specific order for node placement, in a binary search tree all the elements on the left side of a node are smaller than the node itself, and el
10 min read
How to Read File into String in C++? In C++, file handling allows us to read and write data to an external file from our program. In this article, we will learn how to read a file into a string in C++. Reading Whole File into a C++ StringTo read an entire file line by line and save it into std::string, we can use std::ifstream class to
2 min read
Search String using binary_search() function in C++ STL The in-built STL library function binary_search() for searching whether a given string is present or not in the given string array. Binary search is a divide and conquers approach. The idea behind the binary search algorithm is to keep dividing the array in half until the element is found, or all th
2 min read