将链表转换为二叉搜索树?

时间:2011-03-30 21:20:00

标签: c algorithm data-structures

给出一个循环的双向链表...如何将其转换为二进制搜索树..

问题发现于 http://rajeevprasanna.blogspot.com/2011/02/convert-binary-tree-into-doubly-linked.html

我试着写相同的代码,但它窒息!!拜托,这里的一些建议会很好。另外,我如何找到链表的中间..请谈谈代码(C或C ++代码),如果可能的话,小例子也可以。

通过我上面提供的文章(URL),BST到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;
}

1 个答案:

答案 0 :(得分:1)

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;
}