將二叉排序樹轉換爲有序的雙向鏈表,只需調整結點的指針位置。見代碼
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef struct BSTNode
{
int data;
struct BSTNode *left, *right;
} BSTNode, *BSTree;
/*
*在二叉查找樹中查找數據域爲n個結點
*parent是當前結點的父結點,當T是根結點時,parent=NULL
*/
Status BSTSearch(BSTree T, int n, BSTree *parent)
{
if (T == NULL)
return FALSE;
if (n == T->data)
{
*parent = T;
return TRUE;
}
if (n < T->data)
{
*parent = T;
return BSTSearch(T->left, n, parent);
}
if (n > T->data)
{
*parent = T;
return BSTSearch(T->right, n, parent);
}
}
/*
*在二叉查找樹中插入數據域爲n的結點
*/
Status BSTInsert(BSTree *T, int n)
{
BSTree parent, s;
parent = NULL; //parent的初始值爲NULL
if (BSTSearch(*T, n, &parent))
return FALSE;
s = (BSTree)malloc(sizeof(BSTNode));
s->data = n;
s->left = s->right = NULL;
if (parent == NULL)
*T = s;
else if (n < parent->data)
parent->left = s;
else
parent->right = s;
return TRUE;
}
/*
*中序遍歷二叉查找樹,結果是一個遞增數列
*/
void MidTraverse(BSTree T)
{
if (T != NULL)
{
MidTraverse(T->left);
printf("%d ", T->data);
MidTraverse(T->right);
}
}
/*
*將二叉排序樹轉換爲有序的雙向鏈表,只需調整結點的指針位置
*head指向有序雙向鏈表的第一個結點,tail指向最後一個結點
*/
void ToLinkedList(BSTree T, BSTree *head, BSTree *tail)
{
BSTree lt, rh;
if (T == NULL)
*head = *tail = NULL;
else
{
ToLinkedList(T->left, head, <);
ToLinkedList(T->right, &rh, tail);
if (lt)
{
lt->right = T;
T->left = lt;
}
else
*head = T;
if (rh)
{
T->right = rh;
rh->left = T;
}
else
*tail = T;
}
}
int main(void)
{
int i;
int a[7] = {10, 6, 14, 4, 8, 16, 12};
BSTree head, tail, p;
BSTree T = NULL;
for (i = 0; i < 7; i++)
BSTInsert(&T, a[i]);
MidTraverse(T);
printf("\n");
ToLinkedList(T, &head, &tail);
p = head;
while (p) //向後遍歷有序雙向鏈表,結果是一個遞增序列
{
printf("%d ", p->data);
p = p->right;
}
printf("\n");
p = tail;
while (p) //向前遍歷有序雙向鏈表,結果是一個遞減序列
{
printf("%d ", p->data);
p = p->left;
}
printf("\n");
return 0;
}