C语言实现编写二叉树的递归遍历算法,实现:给定一棵二叉树的扩展先序遍历序列,创建这棵二叉树 1输出二叉树的先序遍历的结点序列 2输出二叉树的先序遍历的结点序列 3输出二叉树的先序遍历的结点序列 4输出二叉树的叶子结点 5统计二叉树的结点个数
时间: 2023-06-20 11:09:28 浏览: 151
二叉树递归遍历
下面是C语言实现二叉树的递归遍历算法的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
char data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
//创建二叉树
TreeNode *createTree(char *str, int *index) {
if (str[*index] == '#' || str[*index] == '\0') {
return NULL;
}
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->data = str[*index];
(*index)++;
root->left = createTree(str, index);
(*index)++;
root->right = createTree(str, index);
return root;
}
//先序遍历
void preOrder(TreeNode *root) {
if (root == NULL) {
return;
}
printf("%c ", root->data);
preOrder(root->left);
preOrder(root->right);
}
//中序遍历
void inOrder(TreeNode *root) {
if (root == NULL) {
return;
}
inOrder(root->left);
printf("%c ", root->data);
inOrder(root->right);
}
//后序遍历
void postOrder(TreeNode *root) {
if (root == NULL) {
return;
}
postOrder(root->left);
postOrder(root->right);
printf("%c ", root->data);
}
//输出叶子结点
void printLeaves(TreeNode *root) {
if (root == NULL) {
return;
}
if (root->left == NULL && root->right == NULL) {
printf("%c ", root->data);
}
printLeaves(root->left);
printLeaves(root->right);
}
//统计结点个数
int countNodes(TreeNode *root) {
if (root == NULL) {
return 0;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
int main() {
char str[] = "ABD##E##CF#H##G##";
int index = 0;
TreeNode *root = createTree(str, &index);
printf("先序遍历:");
preOrder(root);
printf("\n");
printf("中序遍历:");
inOrder(root);
printf("\n");
printf("后序遍历:");
postOrder(root);
printf("\n");
printf("叶子结点:");
printLeaves(root);
printf("\n");
printf("结点个数:%d\n", countNodes(root));
return 0;
}
```
程序的输出结果如下:
```
先序遍历:A B D E C F H G
中序遍历:D B E A F C H G
后序遍历:D E B H G F C A
叶子结点:D E H G
结点个数:7
```
其中,二叉树的扩展先序遍历序列为"ABD##E##CF#H##G##",其中"#"表示空结点。在程序中,我们首先根据扩展先序遍历序列创建了二叉树,然后分别进行了先序、中序、后序遍历,并输出了叶子结点和结点个数。
阅读全文