二叉树的扩展遍历序列生成二叉树,并将二叉树的三种遍历序列全部输出c语言
时间: 2023-06-22 22:21:10 浏览: 81
好的,以下是 C 语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结点的定义
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 根据扩展遍历序列生成二叉树
TreeNode* buildTree(char* s) {
if (*s == '\0') {
return NULL;
}
// 构造根结点
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = *s - '0';
root->left = NULL;
root->right = NULL;
// 构造左子树
char* p = s + 1;
while (*p != '\0' && (*p == '(' || *p == ')')) {
p++;
}
root->left = buildTree(p);
// 构造右子树
p++;
while (*p != '\0' && (*p == '(' || *p == ')')) {
p++;
}
root->right = buildTree(p);
return root;
}
// 前序遍历
void preorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// 中序遍历
void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
// 后序遍历
void postorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->val);
}
int main() {
char* s = "1(2(4()())(5()()))(3(6()())(7()()))";
TreeNode* root = buildTree(s);
printf("前序遍历结果:");
preorderTraversal(root);
printf("\n中序遍历结果:");
inorderTraversal(root);
printf("\n后序遍历结果:");
postorderTraversal(root);
printf("\n");
return 0;
}
```
输出结果为:
```
前序遍历结果:1 2 4 5 3 6 7
中序遍历结果:4 2 5 1 6 3 7
后序遍历结果:4 5 2 6 7 3 1
```
阅读全文