首页 > 代码库 > Convert Binary Search Tree (BST) to Sorted Doubly-Linked List

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

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

 

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