先序序列二叉树的创建c语言
时间: 2023-12-12 12:34:44 浏览: 107
以下是先序序列二叉树的创建C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* createTree(int* preorder, int preorderSize) {
if (preorderSize == 0) {
return NULL;
}
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = preorder[0];
int i = 1;
while (i < preorderSize && preorder[i] <= root->val) {
i++;
}
root->left = createTree(preorder + 1, i - 1);
root->right = createTree(preorder + i, preorderSize - i);
return root;
}
int main() {
int preorder[] = {5, 3, 2, 4, 7, 6, 8};
int preorderSize = sizeof(preorder) / sizeof(int);
struct TreeNode* root = createTree(preorder, preorderSize);
return 0;
}
```
阅读全文