c语言由先序序列和中序序列构造二叉树代码
时间: 2023-12-12 16:04:00 浏览: 80
由先序与中序序列构造二叉树
以下是C语言由先序序列和中序序列构造二叉树的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {
if (preorderSize == 0 || inorderSize == 0) {
return NULL;
}
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = preorder[0];
int i;
for (i = 0; i < inorderSize; i++) {
if (inorder[i] == preorder[0]) {
break;
}
}
root->left = buildTree(preorder + 1, i, inorder, i);
root->right = buildTree(preorder + i + 1, preorderSize - i - 1, inorder + i + 1, inorderSize - i - 1);
return root;
}
int main() {
int preorder[] = {3,9, 20, 15, 7};
int inorder[] = {9, 3, 15, 20, 7};
struct TreeNode* root = buildTree(preorder, 5, inorder, 5);
return 0;
}
```
阅读全文