题意:
convert bst to double-linked list
代码:
struct BSTree {
BSTree(int v) :val(v), left(NULL), right(NULL) {}
~BSTree() {
if (left) delete left;
if (right) delete right;
}
int val;
BSTree* left, *right;
};
struct DoubleLinkedList {
DoubleLinkedList(int v) : val(v), prev(NULL), next(NULL) {}
~DoubleLinkedList() {
if (next)
delete next;
}
DoubleLinkedList *prev, *next;
int val;
};
void insert(int val, BSTree*& root) {
if (!root)
root = new BSTree(val);
else if (root->val > val)
insert(val, root->left);
else if (root->val < val)
insert(val, root->right);
}
BSTree* buildBST() {
ifstream ifstr("bst_to_double_linked_list.txt");
if (!ifstr)
assert(0);
string line;
getline(ifstr, line);
int val;
istringstream istringstr(line);
BSTree* root = NULL;
while (istringstr >> val) {
insert(val, root);
}
return root;
}
void traverse_tree(BSTree* root) {
if (root) {
traverse_tree(root->left);
cout << root->val << endl;
traverse_tree(root->right);
}
}
// 理解这两个指针引用,特别是第一个:prevElem
void convert_bst_to_dllist(BSTree* root, DoubleLinkedList* & prevElem, DoubleLinkedList*& head) {
if (root->left)
convert_bst_to_dllist(root->left, prevElem, head);
DoubleLinkedList* newElem = new DoubleLinkedList(root->val);
if (prevElem) {
prevElem->next = newElem;
newElem->prev = prevElem;
}
if (head == NULL)
head = newElem;
prevElem = newElem;
if (root->right)
convert_bst_to_dllist(root->right, prevElem, head);
}
void traverse_dllist(DoubleLinkedList* list_head) {
cout << "positive sequence:" << endl;
while (list_head && list_head->next) {
cout << list_head->val << " ";
list_head = list_head->next;
}
if (list_head)
cout << list_head->val << endl;
cout << "negative sequence:" << endl;
while (list_head && list_head->prev) {
cout << list_head->val << " ";
list_head = list_head->prev;
}
if (list_head)
cout << list_head->val << endl;
}
int main() {
BSTree* root = buildBST();
//traverse_tree(root);
DoubleLinkedList* list_head = NULL, *prevElem = NULL;
if (root)
convert_bst_to_dllist(root, prevElem, list_head);
if (list_head)
traverse_dllist(list_head);
delete list_head;
delete root;
return 0;
}