给出了一个循环双链表…如何将其转换为二进制搜索树。。
问题在
http://rajeevprasanna.blogspot.com/2011/02/convert-binary-tree-into-doubly-linked.html
我试着写同样的代码,但它哽咽了!!拜托,这里有些建议会很好。另外,我怎样才能找到链接列表的中间请用代码(C或C++代码)进行讨论,如果可能的话,小例子就好了。
浏览我在上面提供的文章(url),bst to linked list是一个很好的练习。我试着追随同一个校长,但我的计划被扼杀了…请帮忙。。。
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;
}