题目:输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
思路:head指向双向链表头,x指向双向链表尾,中序遍历二叉树,每当遍历一个到一个节点时,将它链接到双向链表尾。
#include <iostream>
using namespace std;
#define MAX 10
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
}*head, *x;
BSTreeNode* InsertTree(BSTreeNode* root, BSTreeNode* z)
{
BSTreeNode* x = root;
BSTreeNode* y = NULL;
while (x) {
y = x;
if (x->m_nValue > z->m_nValue) {
x = x->m_pLeft;
}
else if (x->m_nValue < z->m_nValue){
x = x->m_pRight;
}
else {
cout << "duplicate value during inserting "<< z->m_nValue <<"!\n";
return root;
}
}
if (!y) {
root = z;
}
else {
if (y->m_nValue > z->m_nValue) {
y->m_pLeft = z;
}
else {
y->m_pRight = z;
}
}
return root;
}
void DeleteDoubleList(BSTreeNode* head)
{
BSTreeNode* p = head;
while (head) {
p = head->m_pRight;
delete head;
head = p;
}
}
void PrintDoubleList(BSTreeNode* head)
{
BSTreeNode* p;
while (head) {
p = head->m_pRight;
cout<<head->m_nValue<<" ";
head = p;
}
cout << endl;
}
void ConvertCurrentNode(BSTreeNode* root)
{
cout << root->m_nValue << " ";
if (!head) {
head = root;
x = root;
}
else {
x->m_pRight = root;
root->m_pLeft = x;
x = root;
}
}
void ConvertToDoubleList(BSTreeNode* root)
{
if (!root) return;
if (root->m_pLeft) {
ConvertToDoubleList(root->m_pLeft);
}
ConvertCurrentNode(root);
if (root->m_pRight) {
ConvertToDoubleList(root->m_pRight);
}
}
int main()
{
head = NULL;
x = NULL;
BSTreeNode* root = NULL;
int a[MAX] = {10,6,14,4,8,12,16, 17, 5, 11};
for (int i = 0; i < MAX; ++i) {
BSTreeNode* z = new BSTreeNode();
z->m_nValue = a[i];
z->m_pLeft = NULL;
z->m_pRight = NULL;
root = InsertTree(root, z);
}
ConvertToDoubleList(root);
cout << endl;
cout << "After convert to double list:\n";
PrintDoubleList(head);
DeleteDoubleList(head);
head = NULL;
cout << "After delete double list:\n";
PrintDoubleList(head);
return 0;
}