用C语言以链表的形式写二叉排序树
时间: 2023-05-30 17:03:00 浏览: 57
```
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
void insert(TreeNode **root, int data) {
TreeNode *newNode = malloc(sizeof(TreeNode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
if (*root == NULL) {
*root = newNode;
return;
}
TreeNode *current = *root;
while (1) {
if (data < current->data) {
if (current->left == NULL) {
current->left = newNode;
break;
}
current = current->left;
} else {
if (current->right == NULL) {
current->right = newNode;
break;
}
current = current->right;
}
}
}
void printInOrder(TreeNode *root) {
if (root == NULL) {
return;
}
printInOrder(root->left);
printf("%d ", root->data);
printInOrder(root->right);
}
int main() {
TreeNode *root = NULL;
insert(&root, 5);
insert(&root, 7);
insert(&root, 2);
insert(&root, 8);
insert(&root, 1);
insert(&root, 6);
insert(&root, 3);
printInOrder(root);
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)
![](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)