#include <bits/stdc++.h>
using
namespace
std;
class
Node {
public
:
int
data;
Node *left, *right;
};
int
countNodes(Node* head)
{
int
count = 0;
Node* temp = head;
while
(temp) {
temp = temp->right;
count++;
}
return
count;
}
Node* sortedListToBSTRecur(
Node** head_ref,
int
n)
{
if
(n <= 0)
return
NULL;
Node* left = sortedListToBSTRecur(
head_ref, n / 2);
Node* root = *head_ref;
root->left = left;
*head_ref = (*head_ref)->right;
root->right
= sortedListToBSTRecur(
head_ref, n - n / 2 - 1);
return
root;
}
Node* sortedListToBST(Node* head)
{
int
n = countNodes(head);
return
sortedListToBSTRecur(
&head, n);
}
Node* extractLeafList(Node* root,
Node** head_ref)
{
if
(root == NULL)
return
NULL;
if
(root->left == NULL
&& root->right == NULL) {
root->right = *head_ref;
if
(*head_ref != NULL)
(*head_ref)->left = root;
*head_ref = root;
return
NULL;
}
root->right = extractLeafList(root->right,
head_ref);
root->left = extractLeafList(root->left,
head_ref);
return
root;
}
Node* newNode(
int
data)
{
Node* node =
new
Node();
node->data = data;
node->left = NULL;
node->right = NULL;
return
node;
}
void
print(Node* root)
{
if
(root != NULL) {
print(root->left);
cout << root->data
<<
" "
;
print(root->right);
}
}
void
printList(Node* head)
{
while
(head) {
cout << head->data <<
" "
;
head = head->right;
}
}
int
main()
{
Node* head = NULL;
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(6);
root->left->left->left = newNode(7);
root->left->left->right = newNode(8);
root->right->right->left = newNode(9);
root->right->right->right = newNode(10);
root = extractLeafList(
root, &head);
root = sortedListToBST(head);
print(root);
return
0;
}