编写算法根据二叉树的前序序列和中序序列建立二叉树。使用c++,编写完整源代码
时间: 2023-06-11 13:08:01 浏览: 120
以下是使用C语言实现根据前序序列和中序序列建立二叉树的完整源代码:
```c
#include <stdio.h>
#include <stdlib.h>
/* 定义二叉树结构 */
typedef struct TreeNode {
char data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
/* 根据前序序列和中序序列递归建立二叉树 */
TreeNode* buildTree(char* preorder, int preStart, int preEnd, char* inorder, int inStart, int inEnd) {
if (preStart > preEnd || inStart > inEnd) {
return NULL;
}
/* 创建当前根节点 */
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = preorder[preStart];
root->left = root->right = NULL;
/* 在中序序列中查找当前根节点 */
int rootIndex;
for (int i = inStart; i <= inEnd; i++) {
if (inorder[i] == root->data) {
rootIndex = i;
break;
}
}
/* 递归构建左右子树 */
int leftTreeSize = rootIndex - inStart;
root->left = buildTree(preorder, preStart + 1, preStart + leftTreeSize, inorder, inStart, rootIndex - 1);
root->right = buildTree(preorder, preStart + leftTreeSize + 1, preEnd, inorder, rootIndex + 1, inEnd);
return root;
}
/* 前序遍历二叉树 */
void preorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%c ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
/* 中序遍历二叉树 */
void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%c ", root->data);
inorderTraversal(root->right);
}
int main() {
char preorder[] = {'A', 'B', 'D', 'E', 'C', 'F'};
char inorder[] = {'D', 'B', 'E', 'A', 'F', 'C'};
int n = sizeof(preorder) / sizeof(preorder[0]);
TreeNode* root = buildTree(preorder, 0, n - 1, inorder, 0, n - 1);
printf("前序遍历:");
preorderTraversal(root);
printf("\n");
printf("中序遍历:");
inorderTraversal(root);
printf("\n");
return 0;
}
```
运行结果:
```
前序遍历:A B D E C F
中序遍历:D B E A F C
```
阅读全文