#include <bits/stdc++.h>
using namespace std;
// tree node is defined
class TreeNode
{
public:
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int data)
{
val = data;
left = NULL;
right = NULL;
}
};
void inorder(TreeNode *root)
{
if (!root)
return;
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
// recursive function to construct the tree from
// level order traversal
TreeNode *constructBSTRecur(TreeNode *root, int data)
{
if (root == NULL)
return new TreeNode(data);
// if data value is less than root go towards left
if (root->val > data)
root->left = constructBSTRecur(root->left, data);
// if data value is more than root go towards right
if (root->val < data)
root->right = constructBSTRecur(root->right, data);
return root;
}
// function to construct tree from level order traversal
TreeNode *constructBst(vector<int> &arr, int n)
{
TreeNode *root = NULL;
// loop through each element one by one
for (int i = 0; i < n; i++)
{
root = constructBSTRecur(root, arr[i]);
}
return root;
}
int main()
{
// below is the level order traversal of the example tree
vector<int> arr{3, 2, 5, 1, 4, 6};
cout << "Creating BST from the level order traversal\n";
TreeNode *root = constructBst(arr, arr.size());
cout << "BST created\n";
cout << "Inorder traversal of the BST is:\n";
inorder(root);
return 0;
}
Output
Creating BST from the level order traversal
BST created
Inorder traversal of the BST is:
1 2 3 4 5 6
0 Comments