中序遍历实现数组元素排序
struct data arr[6] = { 100, "aa", 50, "bb", 40, "cc", 120, "dd", 110, "oo", 130, "qq" };
实现输出:
arr[6] = { 40, "cc", 50, "bb",100, "aa", 110, "oo", 120, "dd", 130, "qq" };
代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 有规律的二叉树
// 1.创建节点数据结构体
struct data
{
int first; // 关键字
char second[20]; // 数据
};
// 2.创建二叉树节点结构体
struct binTreeNode
{
struct data element; // 节点数据 数据域
struct binTreeNode* LChild; // 左子树指针
struct binTreeNode* RChild; // 右子树指针
};
// 3.创建数的节点
struct binTreeNode* CreateNode(struct data element);
// 4.插入节点
void InsertNode(struct binTreeNode* tree, struct data element);
// 5.打印数据 中序遍历
void printTree(struct binTreeNode* tree);
int main()
{
// 创建数据结构体对象
struct data arr[6] = { 100, "aa", 50, "bb", 40, "cc", 120, "dd", 110, "oo", 130, "qq" };
// 创建二叉树节点
struct binTreeNode* tree = CreateNode(arr[0]);
// 循环插入数据
for (int i = 0; i < 6; i++)
{
// 插入数据
InsertNode(tree, arr[i]);
}
// 中序遍历 输出数据
printTree(tree);
system("pause");
return 0;
}
// 3.创建数的节点
struct binTreeNode* CreateNode(struct data element)
{
// 创建节点 动态申请内存空间
struct binTreeNode* tree = (struct binTreeNode*)malloc(sizeof(struct binTreeNode));
// 判空
if (NULL == tree)
{
return NULL;
}
// 给节点结构体赋值
//tree->element.first = -1;
tree->element = element;
// 将数组置0
//memset(tree->element.second, 0, 20);
tree->LChild = NULL;
tree->RChild = NULL;
return tree;
}
// 4.插入节点
void InsertNode(struct binTreeNode* tree, struct data element)
{
// 定义两个移动指针
struct binTreeNode* moveNode = tree;
struct binTreeNode* movePreNode = NULL;
// 找要插入的位置 遍历移动指针 当移动的指针指向空时,表示找到要插入的位置了
while (NULL != moveNode)
{
// 移动之前记录当前要移动的指针
movePreNode = moveNode;
// 移动 根据关键字判断要往左移动还是要往右移动
if (element.first < moveNode->element.first)
{
// 左移
moveNode = moveNode->LChild;
}
else if (element.first > moveNode->element.first)
{
// 右移
moveNode = moveNode->RChild;
}
else
{
// 相等处理(关键字相等) 采用保留最后一个的插入元素
strcpy(moveNode->element.second, element.second);
return;
}
}
// 找到要插入的位置了movePreNode就是要插入的父节点, 创建要插入的节点
struct binTreeNode* newNode = (struct binTreeNode*)malloc(sizeof(struct binTreeNode));
// 判空
if (NULL == newNode)
{
return;
}
// 给节点结构体赋值
newNode->element = element;
newNode->LChild = NULL;
newNode->RChild = NULL;
// 判断要插入的节点是否为空
if (tree == NULL)
{
// 插入的节点插入到父节点上
tree = newNode;
}
else
{
if (NULL != movePreNode)
{
// 判断要插入的移动节点是父节点(movePreNode)的左边还是右边
if (movePreNode->element.first > element.first)
{
// 插入到左边
movePreNode->LChild = newNode;
}
else
{
// 插入到右边
movePreNode->RChild = newNode;
}
}
}
}
// 5.打印数据 中序遍历 利用递归
void printTree(struct binTreeNode* tree)
{
// 注意要当tree不为空时才进行操作
if (NULL != tree)
{
printTree(tree->LChild);
printf("%d\t%s\n", tree->element.first, tree->element.second);
printTree(tree->RChild);
}
}
程序运行结果: