Given a Circularly doubly linked list... How can i convert it into Binary Search Tree..
The question is found at http://rajeevprasanna.blogspot.com/2011/02/convert-binary-tree-into-doubly-linked.html
I tried to write the code for the same, but it choked!! Ple开发者_Python百科ase, some suggestions here would be good. Also, how can i find the middle of the linked list.. Please talk in terms of code (C or C++ code) and if possible small example would be good else fine.
Going through the article(URL) that i provided above, BST to Linked List was a good excercise. I tried to follow on the same principal, but my program choked... Please help...
Node ListToTree(Node head)
{
if(head == NULL)
return NULL;
Node hleft = NULL, hright = NULL;
Node root = head;
hleft = ListToTree(head->left);
head->left = NULL;
root->left = hleft;
hright = ListToTree(head->right);
head->right = NULL;
root->right = hright;
return root;
}
class Node {
Node *prev, *next;
int value;
}
void listToTree(Node * head) {
if (head == null)
return;
if (head->next == head) {
head->prev = null;
head->next = null;
return head;
}
if (head->next->next == head) {
head->prev = null;
head->next->next = null;
head->next->prev = null;
return head;
}
Node *p1 = head, *p2 = head->prev;
while (p1->value < p2.value)
p1 = p1->next, p2 = p2->prev;
Node * root = p1;
root->prev->next = head;
root->next->prev = head->prev;
root->prev = listToTree(head);
root->next = listToTree(root->next);
return root;
}
精彩评论