由前序遍历和后序遍历构建二叉树的C语言代码
时间: 2023-11-19 10:05:06 浏览: 86
以下是由前序遍历和后序遍历构建二叉树的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* buildTreeHelper(int* preorder, int preStart, int preEnd, int* inorder, int inStart, int inEnd, int* postorder, int postStart, int postEnd) {
if (preStart > preEnd || inStart > inEnd || postStart > postEnd) {
return NULL;
}
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = preorder[preStart];
int inIndex = 0;
for (int i = inStart; i <= inEnd; i++) {
if (inorder[i] == root->val) {
inIndex = i;
break;
}
}
int leftTreeSize = inIndex - inStart;
int rightTreeSize = inEnd - inIndex;
root->left = buildTreeHelper(preorder, preStart + 1, preStart + leftTreeSize, inorder, inStart, inIndex - 1, postorder, postStart, postStart + leftTreeSize - 1);
root->right = buildTreeHelper(preorder, preStart + leftTreeSize + 1, preEnd, inorder, inIndex + 1, inEnd, postorder, postStart + leftTreeSize, postEnd - 1);
return root;
}
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize, int* postorder, int postorderSize) {
return buildTreeHelper(preorder, 0, preorderSize - 1, inorder, 0, inorderSize - 1, postorder, 0, postorderSize - 1);
}
void printTree(struct TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
printTree(root->left);
printTree(root->right);
}
int main() {
int preorder[] = {1, 2, 4, 5, 3, 6, 7};
int inorder[] = {4, 2, 5, 1, 6, 3, 7};
int postorder[] = {4, 5, 2, 6, 7, 3, 1};
int size = sizeof(preorder) / sizeof(preorder[0]);
struct TreeNode* root = buildTree(preorder, size, inorder, size, postorder, size);
printf("前序遍历结果:");
printTree(root);
printf("\n");
return 0;
}
```
这里假设前序遍历为preorder,后序遍历为postorder,中序遍历为inorder。函数buildTreeHelper()用于构建二叉树,其中preStart和preEnd表示当前前序遍历序列的起始和结束位置,inStart和inEnd表示当前中序遍历序列的起始和结束位置,postStart和postEnd表示当前后序遍历序列的起始和结束位置。在函数中,首先根据前序遍历序列的第一个元素创建根节点root,然后在中序遍历序列中查找到root的位置inIndex,进而计算出左子树的大小leftTreeSize和右子树的大小rightTreeSize。接下来,分别递归构建左子树和右子树,并将根节点的左右子树指针指向左右子树的根节点。最后,返回根节点。函数buildTree()是对buildTreeHelper()的包装,传入前序遍历序列、中序遍历序列、后序遍历序列的起始位置和大小。函数printTree()用于前序遍历打印二叉树,方便验证结果。主函数中定义了三个遍历序列,通过buildTree()创建二叉树并打印前序遍历结果。
阅读全文