(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; }
时间: 2024-12-25 11:37:25