c语言已知二叉树先序和中序序列,唯一地构造一棵二叉树并且验证其正确性
时间: 2023-08-21 19:02:34 浏览: 112
是的,可以使用递归的方式来构造二叉树,并且通过比较构造出来的二叉树的先序和中序序列是否与给定的序列一致来验证其正确性。
具体步骤如下:
1.将先序序列的第一个元素作为根节点。
2.在中序序列中找到根节点所在的位置,将序列分为左子树和右子树两部分。
3.根据左子树和右子树的长度,在先序序列中找到左子树和右子树的元素。
4.递归构造左子树和右子树,连接到根节点上。
5.最后,比较构造出来的二叉树的先序和中序序列是否与给定的序列一致。
代码实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct TreeNode {
char val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode* buildTree(char* preorder, char* inorder, int preStart, int preEnd, int inStart, int inEnd) {
if (preStart > preEnd || inStart > inEnd) {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = preorder[preStart];
root->left = NULL;
root->right = NULL;
int i;
for (i = inStart; i <= inEnd; i++) {
if (inorder[i] == root->val) {
break;
}
}
int leftLen = i - inStart;
root->left = buildTree(preorder, inorder, preStart + 1, preStart + leftLen, inStart, i - 1);
root->right = buildTree(preorder, inorder, preStart + leftLen + 1, preEnd, i + 1, inEnd);
return root;
}
void preorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%c ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%c ", root->val);
inorderTraversal(root->right);
}
int main() {
char preorder[] = "ABDECF";
char inorder[] = "DBEAFC";
int len = strlen(preorder);
TreeNode* root = buildTree(preorder, inorder, 0, len - 1, 0, len - 1);
printf("Preorder traversal: ");
preorderTraversal(root);
printf("\n");
printf("Inorder traversal: ");
inorderTraversal(root);
printf("\n");
return 0;
}
```
输出结果为:
```
Preorder traversal: A B D E C F
Inorder traversal: D B E A F C
```
可以看到,构造出来的二叉树的先序和中序序列与给定的序列一致,说明构造正确。
阅读全文
相关推荐
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)