用c语言设计二叉树的建立、中序遍历、并将二叉链表存储转换成顺序存储的算法
时间: 2024-01-12 11:04:11 浏览: 109
好的,让我来回答你的问题。
1. 二叉树的建立
二叉树的建立可以通过递归的方式实现。我们可以定义一个函数buildTree,通过传入的参数构建二叉树。具体实现如下:
```c
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
TreeNode* buildTree() {
int val;
scanf("%d", &val);
if (val == -1) {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = val;
root->left = buildTree();
root->right = buildTree();
return root;
}
```
2. 二叉树的中序遍历
二叉树的中序遍历可以通过递归的方式实现。我们可以定义一个函数inorderTraversal,通过传入的参数遍历二叉树并输出节点的值。具体实现如下:
```c
void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
```
3. 二叉链表存储的转换成顺序存储
二叉链表存储的转换成顺序存储可以通过中序遍历实现。我们可以先中序遍历二叉树,将节点的值存储在一个数组中,然后再将数组转换成顺序存储。具体实现如下:
```c
void inorderTraversal(TreeNode* root, int* nums, int* index) {
if (root == NULL) {
return;
}
inorderTraversal(root->left, nums, index);
nums[(*index)++] = root->val;
inorderTraversal(root->right, nums, index);
}
int* convertToSeq(TreeNode* root, int* returnSize) {
*returnSize = 0;
inorderTraversal(root, NULL, returnSize);
int* nums = (int*)malloc(sizeof(int) * (*returnSize));
int index = 0;
inorderTraversal(root, nums, &index);
return nums;
}
```
以上就是用c语言设计二叉树的建立、中序遍历、并将二叉链表存储转换成顺序存储的算法。
阅读全文
相关推荐















