用c语言
时间: 2024-02-28 13:54:39 浏览: 10
以下是用 C 语言实现二叉排序树的建立的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode* create_node(int val) {
TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
void insert(TreeNode **root, int val) {
if (*root == NULL) {
*root = create_node(val);
return;
}
if (val < (*root)->val) {
insert(&(*root)->left, val);
} else {
insert(&(*root)->right, val);
}
}
void inorder(TreeNode *root) {
if (root == NULL) {
return;
}
inorder(root->left);
printf("%d ", root->val);
inorder(root->right);
}
int main() {
TreeNode *root = NULL;
insert(&root, 5);
insert(&root, 3);
insert(&root, 7);
insert(&root, 1);
insert(&root, 9);
inorder(root); // 输出:1 3 5 7 9
return 0;
}
```
在这个示例代码中,我们定义了一个 `TreeNode` 结构体来表示二叉排序树中的节点,其中包含了节点的值 `val`、左子树指针 `left` 和右子树指针 `right`。另外,我们定义了 `create_node` 函数用于创建一个新节点,以及 `insert` 函数用于插入节点。在 `insert` 函数中,我们使用了指向指针的指针,以便能够修改根节点的值。最后,我们还定义了 `inorder` 函数用于中序遍历二叉排序树,并输出节点的值。
在 `main` 函数中,我们首先创建了一个空的二叉排序树 `root`,然后依次插入了节点 5、3、7、1 和 9,最后调用 `inorder` 函数对二叉排序树进行中序遍历,并输出节点的值。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)