代码改变世界

Convert Binary Search Tree (BST) to Sorted Doubly-Linked List

2015-01-16 07:46  李涛的技术博客  阅读(324)  评论(0编辑  收藏  举报

(http://leetcode.com/2010/11/convert-binary-search-tree-bst-to.html)

Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list.

Code:

void treeToDoublyList(Node *p, Node *& prev, Node *& head)
{
    if (!p)
        return;
    treeToDoublyList(p->left, prev, head);

    p->left = prev;
    if (prev)
        prev->right = p;
    else
        head = p;
    prev = p;

    treeToDoublyList(p->right, prev, head);
}

Node* treeToDoublyList(Node* root)
{
    Node* prev = NULL;
    Node* head = NULL;
    treeToDoublyList(root, prev, head);
    head->left = prev;
    prev->right= head;

    return head;
}