Single Linked List to BST
/***
Given
a singly linked list where elements are sorted in ascending order,
convert
it to a height balanced BST.
IDEA:
1)
balanced BST should be started from the median O(nlogn)
2)
construct in order, O(n)
***/
#include<iostream>
using namespace std;
struct node {
int val;
node *next;
node(int v) {
this->val = v;
this->next = nullptr;
}
};
struct tnode {
int val;
tnode *left, *right;
tnode(int v) {
this->val = v;
this->right = nullptr;
this->left = nullptr;
}
};
tnode *ll2bst(node *n, int index) {
//base
case
if(index == 0) {
return nullptr;
}
int front = index/2;
node *t = n;
while(front!=0) {
t= t->next;
front--;
}
tnode *tree = new tnode(t->val);
t = t->next;
tnode *left, *right;
front = index/2;
int back = index-front-1;
left = ll2bst(n, front);
right = ll2bst(t, back);
tree->left = left;
tree->right = right;
return tree;
}
void main() {
node *n[7];
n[6] = new node(7);
for (int i = 5; i>=0; i--)
{
n[i] = new node(i+1);
n[i]->next = n[i+1];
}
tnode *root = ll2bst(n[0], 7);
cout<<"test"<<endl;
}
Comments
Post a Comment