通过先序遍历和中序遍历确定二叉树的程序c语言
时间: 2024-03-14 10:45:19 浏览: 66
二叉树的前序,中序,后序排列C语言程序
以下是通过先序遍历和中序遍历确定二叉树的C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct TreeNode {
char val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* buildTree(char* preorder, char* inorder, int preorderSize, int inorderSize) {
if (preorderSize == 0 || inorderSize == 0) {
return NULL;
}
struct TreeNode *node = (struct TreeNode *)malloc(sizeof(struct TreeNode));
node->val = *preorder;
int i;
for (i = 0; i < inorderSize; i++) {
if (*(inorder + i) == *preorder) {
break;
}
}
node->left = buildTree(preorder + 1, inorder, i, i);
node->right = buildTree(preorder + i + 1, inorder + i + 1, preorderSize - i - 1, inorderSize - i - 1);
return node;
}
void printTree(struct TreeNode *root) {
if (root == NULL) {
return;
}
printf("%c ", root->val);
printTree(root->left);
printTree(root->right);
}
int main() {
char preorder[] = {'A', 'B', 'D', 'E', 'C', 'F'};
char inorder[] = {'D', 'B', 'E', 'A', 'F', 'C'};
struct TreeNode *root = buildTree(preorder, inorder, 6, 6);
printf("先序遍历结果为:");
printTree(root);
return 0;
}
```
此程序实现了通过先序遍历和中序遍历确定二叉树,并输出先序遍历结果。
阅读全文