简体   繁体   English

将链表转换成二进制搜索树?

[英]Convert linked list into binary search tree?

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 有关问题,请访问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!! 我试图写同样的代码,但是很cho! Please, 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. 另外,我怎么能找到链表的中间部分。请以代码(C或C ++代码)的方式进行讨论,如果可能的话,举个小例子会很好。

Going through the article(URL) that i provided above, BST to Linked List was a good excercise. 通过上面我提供的文章(URL),BST到链接列表是一个很好的练习。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM