#include <stdio.h>
#include <stdlib.h>
struct BSTreeNode {
int m_Value;
struct BSTreeNode *m_pLeft;
struct BSTreeNode *m_pRight;
};
void MidOrderVisit(struct BSTreeNode *root)
{
if (root == NULL)
return;
MidOrderVisit(root->m_pLeft);
printf("%d\n", root->m_Value);
MidOrderVisit(root->m_pRight);
}
void CreateList(struct BSTreeNode *root, struct BSTreeNode **list)
{
if (root == NULL)
return;
CreateList(root->m_pLeft, list);
root->m_pLeft = *list;
*list = root;
CreateList(root->m_pRight, list);
}
struct BSTreeNode *CreateDoubleList(struct BSTreeNode *root)
{
struct BSTreeNode *list = NULL;
CreateList(root, &list);
root = list;
root->m_pRight = NULL;
while (root->m_pLeft != NULL) {
root->m_pLeft->m_pRight = root;
root = root->m_pLeft;
}
return list;
}
int InsertNode(struct BSTreeNode **root, int value)
{
struct BSTreeNode *node = *root;
struct BSTreeNode *p;
p = calloc(1, sizeof(struct BSTreeNode));
p->m_Value = value;
while (node != NULL) {
if (node->m_Value == value)
return value;
else if (node->m_Value > value) {
if (node->m_pRight != NULL)
node = node->m_pRight;
else {
node->m_pRight = p;
return 0;
}
}
else {
if (node->m_pLeft != NULL)
node = node->m_pLeft;
else {
node->m_pLeft = p;
return 0;
}
}
}
*root = p;
return 0;
}
void ShowList(struct BSTreeNode *root)
{
struct BSTreeNode *node = root;
printf("prev:");
while (node != NULL) {
printf("%d ", node->m_Value);
if (node->m_pLeft != NULL)
node = node->m_pLeft;
else
break;
}
printf("\nnext:");
while (node != NULL) {
printf("%d ", node->m_Value);
node = node->m_pRight;
}
printf("\n");
}
int main()
{
int i = 0;
int array[9] = {16, 7, 12, 13, 15, 24, 6, 25, 27};
struct BSTreeNode *root = NULL;
struct BSTreeNode *list = NULL;
while (i < 9) {
InsertNode(&root, array[i]);
i++;
}
MidOrderVisit(root);
fflush(NULL);
list = CreateDoubleList(root);
ShowList(list);
return 0;
}把二叉树转化成双向连表
最新推荐文章于 2024-08-14 21:25:09 发布
140

被折叠的 条评论
为什么被折叠?



