#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;
}
};
class ListNode
{
public:
int val;
ListNode *next;
ListNode(int data)
{
val = data;
next = NULL;
}
};
void inorder(TreeNode *root)
{
if (!root)
return;
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
TreeNode *sortedListToBST(ListNode *head)
{
// base cases
// 1.NULL list
if (!head)
return NULL;
// 2. single node list
if (!head->next)
return new TreeNode(head->val);
// find the middle of the linked list
// using floyd's hair & tortoise algorithm
ListNode *slow = head;
ListNode *fast = head;
while (fast->next)
{
// slow pointer moves one step at each iteration
slow = slow->next;
// fast pointer moves two steps at each iteration
fast = fast->next;
// this checking ensures that the 2nd move is possible
if (fast->next)
fast = fast->next;
}
// reach the previous node of the current slow pointer
ListNode *temp = head;
while (temp->next != slow)
{
temp = temp->next;
}
// delink the left part of slow pointer(middle of the list)
temp->next = NULL;
// create root with the middle node
TreeNode *root = new TreeNode(slow->val);
// right part of the middle node
ListNode *ptr = slow->next;
// delink the right part
slow->next = NULL;
// recursively create left subtree from the left part
root->left = sortedListToBST(head);
// recursively create left subtree from the right part
root->right = sortedListToBST(ptr);
return root;
}
int main()
{
// building the tree like the example
ListNode *head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
cout << "Creating self-balancing BST from the sorted list\n";
TreeNode *root = sortedListToBST(head);
cout << "height balanced BST created ...\n";
cout << "root of the BST created is: " << root->val << endl;
cout << "Inorder traversal of the BST\n";
inorder(root);
cout << endl;
return 0;
}
Output
Creating self-balancing BST from the sorted list
height balanced BST created ...
root of the BST created is: 3
Inorder traversal of the BST
1 2 3 4 5
0 Comments