#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;
}
};
// level order traversal for BST
void levelorder(TreeNode *root)
{
if (!root)
return;
queue<TreeNode *> q;
q.push(root);
q.push(NULL);
int count = 1;
cout << "Start of level: " << count << endl;
while (!q.empty())
{
TreeNode *temp = q.front();
q.pop();
if (temp == NULL)
{
if (!q.empty())
{
q.push(NULL);
cout << "\nEnd of level: " << count << endl;
count++;
cout << "Start of level: " << count << endl;
}
else
{
cout << "\nEnd of level: " << count << endl;
}
}
else
{
cout << temp->val << " ";
if (temp->left)
q.push(temp->left);
if (temp->right)
q.push(temp->right);
}
}
}
void inorder(TreeNode *root, vector<int> &store)
{
if (!root)
return;
inorder(root->left, store);
store.push_back(root->val);
inorder(root->right, store);
}
// create a self balanced tree from the sorted array
TreeNode *createBalancedBst(vector<int> &store, int low, int high)
{
if (low > high)
return NULL;
if (low == high)
return new TreeNode(store[low]);
int mid = (low + high) / 2;
TreeNode *root = new TreeNode(store[mid]);
root->left = createBalancedBst(store, low, mid - 1);
root->right = createBalancedBst(store, mid + 1, high);
return root;
}
// helper function to balance the BST
TreeNode *balanceBST(TreeNode *root)
{
vector<int> store;
inorder(root, store);
TreeNode *newroot = createBalancedBst(store, 0, store.size() - 1);
return newroot;
}
int main()
{
// below is the unbalanced BST as per example
TreeNode *root = new TreeNode(2);
root->left = new TreeNode(1);
root->right = new TreeNode(3);
root->right->right = new TreeNode(4);
root->right->right->right = new TreeNode(5);
root->right->right->right->right = new TreeNode(6);
cout << "Level order traversal of the unbalanced BST is :\n";
levelorder(root);
cout << "Balancing the BST ...\n";
TreeNode *newroot = balanceBST(root);
cout << "BST is now balanced...\n";
cout << "Level order traversal of the balanced BST is :\n";
levelorder(newroot);
return 0;
}
Output
Level order traversal of the unbalanced BST is :
Start of level: 1
2
End of level: 1
Start of level: 2
1 3
End of level: 2
Start of level: 3
4
End of level: 3
Start of level: 4
5
End of level: 4
Start of level: 5
6
End of level: 5
Balancing the BST ...
BST is now balanced...
Level order traversal of the balanced BST is :
Start of level: 1
3
End of level: 1
Start of level: 2
1 5
Start of level: 3
2 4 6
End of level: 3
0 Comments