由中序遍历序列和层次遍历序列得出先序遍历的C语言代码优化
时间: 2023-07-24 17:57:12 浏览: 92
首先,根据中序遍历序列和层次遍历序列,我们可以确定树的结构。然后,我们可以利用递归的方法来实现先序遍历。以下是一个C语言的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// 根据中序遍历和层次遍历构建二叉树
struct Node* buildTree(int inorder[], int levelorder[], int inStart, int inEnd) {
if (inStart > inEnd) {
return NULL;
}
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = levelorder[0];
node->left = NULL;
node->right = NULL;
if (inStart == inEnd) {
return node;
}
int i;
int rootIndex = -1;
for (i = inStart; i <= inEnd; i++) {
if (inorder[i] == node->data) {
rootIndex = i;
break;
}
}
int leftCount = rootIndex - inStart;
int rightCount = inEnd - rootIndex;
int* leftInorder = (int*)malloc(leftCount * sizeof(int));
int* rightInorder = (int*)malloc(rightCount * sizeof(int));
int* leftLevelorder = (int*)malloc(leftCount * sizeof(int));
int* rightLevelorder = (int*)malloc(rightCount * sizeof(int));
int li = 0, ri = 0;
for (i = inStart; i < rootIndex; i++) {
leftInorder[li] = inorder[i];
li++;
}
for (i = rootIndex + 1; i <= inEnd; i++) {
rightInorder[ri] = inorder[i];
ri++;
}
int lj = 0, rj = 0;
for (i = 1; i <= leftCount; i++) {
for (int j = 0; j < inEnd + 1; j++) {
if (levelorder[j] == leftInorder[i - 1]) {
leftLevelorder[lj] = levelorder[j];
lj++;
break;
}
}
}
for (i = 1; i <= rightCount; i++) {
for (int j = 0; j < inEnd + 1; j++) {
if (levelorder[j] == rightInorder[i - 1]) {
rightLevelorder[rj] = levelorder[j];
rj++;
break;
}
}
}
node->left = buildTree(leftInorder, leftLevelorder, inStart, rootIndex - 1);
node->right = buildTree(rightInorder, rightLevelorder, rootIndex + 1, inEnd);
free(leftInorder);
free(rightInorder);
free(leftLevelorder);
free(rightLevelorder);
return node;
}
// 先序遍历
void preorderTraversal(struct Node* node) {
if (node != NULL) {
printf("%d ", node->data);
preorderTraversal(node->left);
preorderTraversal(node->right);
}
}
int main() {
int inorder[] = {4, 2, 5, 1, 6, 3};
int levelorder[] = {1, 2, 3, 4, 5, 6};
int length = sizeof(inorder) / sizeof(inorder[0]);
struct Node* root = buildTree(inorder, levelorder, 0, length - 1);
printf("Preorder traversal: ");
preorderTraversal(root);
return 0;
}
```
这段代码首先定义了一个二叉树的结构体,包含节点数据以及左右子节点的指针。然后,通过`buildTree`函数根据中序遍历序列和层次遍历序列构建二叉树。最后,通过`preorderTraversal`函数实现先序遍历,并输出结果。
请注意,这段代码是一种基本实现示例,可能需要根据具体情况进行适当的修改和优化。
阅读全文