在c++下,用数组实现树形排序
时间: 2024-04-29 19:22:53 浏览: 19
树形排序可以使用二叉树实现。节点包含一个值和两个指针,分别指向左子节点和右子节点。通过不断插入节点,可以构建一棵有序二叉树。遍历二叉树时,按照左子节点、根节点、右子节点的顺序遍历,即可得到有序序列。
代码如下:
```c
#include <stdio.h>
#define MAX_SIZE 100
// 二叉树节点结构体
typedef struct Node {
int val;
struct Node *left;
struct Node *right;
} Node;
// 插入节点
void insert(Node **root, int val) {
Node *node = (Node*)malloc(sizeof(Node));
node->val = val;
node->left = node->right = NULL;
if (*root == NULL) {
*root = node;
} else if (val < (*root)->val) {
insert(&((*root)->left), val);
} else {
insert(&((*root)->right), val);
}
}
// 中序遍历
void inorder(Node *root, int *arr, int *i) {
if (root != NULL) {
inorder(root->left, arr, i);
arr[(*i)++] = root->val;
inorder(root->right, arr, i);
}
}
// 树形排序
void tree_sort(int *arr, int n) {
Node *root = NULL;
for (int i = 0; i < n; i++) {
insert(&root, arr[i]);
}
int i = 0;
inorder(root, arr, &i);
}
int main() {
int arr[MAX_SIZE];
int n;
printf("Input the number of elements: ");
scanf("%d", &n);
printf("Input the elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
tree_sort(arr, n);
printf("Sorted array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)