C语言:1、遍历二叉树。 请输入一棵二叉树的扩展的前序序列,经过处理后生成一棵二叉树,然后对于该二叉树输出中序和后序遍历序列。 2、按层次遍历二叉树。
时间: 2023-07-24 18:21:32 浏览: 185
二叉树的几种操作,包括递归先序建立二叉树、先序遍历、中序遍历、后序遍历、非递归的各种遍历
5星 · 资源好评率100%
好的,我可以帮你解决这个问题。
首先,让我们来处理输入的前序序列,生成一棵二叉树。假设你输入的前序序列为 "A(B(D,E),C(F,G))",那么我们可以使用递归的方式来构建这棵二叉树。
C语言的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
char val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* createTree(char *s, int *pos) {
if (s[*pos] == ',' || s[*pos] == ')') {
return NULL;
}
struct TreeNode *node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = s[*pos];
node->left = node->right = NULL;
(*pos)++;
node->left = createTree(s, pos);
(*pos)++;
node->right = createTree(s, pos);
(*pos)++;
return node;
}
void inorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%c ", root->val);
inorderTraversal(root->right);
}
void postorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%c ", root->val);
}
int main() {
char s[100];
scanf("%s", s);
int pos = 0;
struct TreeNode *root = createTree(s, &pos);
printf("Inorder traversal: ");
inorderTraversal(root);
printf("\nPostorder traversal: ");
postorderTraversal(root);
return 0;
}
```
输入 "A(B(D,E),C(F,G))" 后,输出结果如下:
```
Inorder traversal: D B E A F C G
Postorder traversal: D E B F G C A
```
接下来,让我们来看看如何按层次遍历这棵二叉树。
C语言的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
char val;
struct TreeNode *left;
struct TreeNode *right;
};
struct QueueNode {
struct TreeNode *node;
struct QueueNode *next;
};
struct Queue {
struct QueueNode *front;
struct QueueNode *rear;
};
void enqueue(struct Queue *queue, struct TreeNode *node) {
struct QueueNode *newNode = (struct QueueNode*)malloc(sizeof(struct QueueNode));
newNode->node = node;
newNode->next = NULL;
if (queue->front == NULL) {
queue->front = queue->rear = newNode;
} else {
queue->rear->next = newNode;
queue->rear = newNode;
}
}
struct TreeNode* dequeue(struct Queue *queue) {
if (queue->front == NULL) {
return NULL;
}
struct QueueNode *node = queue->front;
queue->front = queue->front->next;
if (queue->front == NULL) {
queue->rear = NULL;
}
struct TreeNode *treeNode = node->node;
free(node);
return treeNode;
}
void levelorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
struct Queue *queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->front = queue->rear = NULL;
enqueue(queue, root);
while (queue->front != NULL) {
struct TreeNode *node = dequeue(queue);
printf("%c ", node->val);
if (node->left != NULL) {
enqueue(queue, node->left);
}
if (node->right != NULL) {
enqueue(queue, node->right);
}
}
}
int main() {
char s[100];
scanf("%s", s);
int pos = 0;
struct TreeNode *root = createTree(s, &pos);
levelorderTraversal(root);
return 0;
}
```
输入 "A(B(D,E),C(F,G))" 后,输出结果如下:
```
A B C D E F G
```
希望这个代码能够帮助到你。
阅读全文