输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ /
6 14
/ / / /
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
typedef struct BSTreeNode
{
int date;
struct BSTreeNode *leftnode;
struct BSTreeNode *rightnode;
}BSTree;
BSTree *head = NULL;
BSTree *tail = NULL;
void creatree(BSTree **node, int num)
{
BSTree *newnode;
newnode = (BSTree *)malloc(sizeof(BSTree));
newnode->date = num;
newnode->leftnode = NULL;
newnode->rightnode = NULL;
BSTree *p = NULL;
BSTree *y = NULL;
p = *node;
while (p)
{
y = p;
if (newnode->date > p->date)
{
p = p->rightnode;
}
else
{
p = p->leftnode;
}
}
if (y == NULL)
{
*node = newnode;
}
else
{
if (y->date > num)
{
y->leftnode = newnode;
}
else
{
y->rightnode = newnode;
}
}
}
void inorder(BSTree *node, void(*TreeLink)(BSTree *node))
{
if (node != NULL)
{
inorder((node->leftnode), TreeLink);
TreeLink(node);
inorder((node->rightnode), TreeLink);
}
}
void TreeLink(BSTree *node)
{
node->leftnode=tail;
if (tail==NULL)
{
head = node;
}
else
{
tail->rightnode = node;
}
tail = node;
printf("%d ", node->date);
}
void main()
{
int a[8] = { 10, 6, 14, 4, 8, 12, 16 };
BSTree *node=NULL;
for (int i = 0; i < 7; i++)
{
creatree(&node, a[i]);
}
inorder(node,TreeLink);
system("pause");
}
把二元查找树转变成排序的双向链表
内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:https://www.heiqu.com/25917bffa81a12a9011c64d8075e50a3.html