以二叉链表为存储结构,编写算法建立一棵二叉树,并按前序遍历次序打印二叉树中的所有叶子结点。
时间: 2024-03-26 17:16:47 浏览: 19
算法步骤:
1. 定义二叉树的结构体和建立二叉树的函数。
2. 编写前序遍历函数和打印叶子结点函数。
3. 在主函数中调用建立二叉树函数,然后依次调用前序遍历函数和打印叶子结点函数。
参考代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结构体
typedef struct TreeNode {
char data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 建立二叉树函数
TreeNode* createTree() {
char ch;
scanf("%c", &ch);
if (ch == '#') { // 如果输入的是 #,表示该结点为空
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = ch;
root->left = createTree();
root->right = createTree();
return root;
}
// 前序遍历函数
void preorderTraverse(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%c ", root->data);
preorderTraverse(root->left);
preorderTraverse(root->right);
}
// 打印叶子结点函数
void printLeafNode(TreeNode* root) {
if (root == NULL) {
return;
}
if (root->left == NULL && root->right == NULL) { // 如果该结点没有左右子树,即为叶子结点
printf("%c ", root->data);
}
printLeafNode(root->left);
printLeafNode(root->right);
}
int main() {
printf("请输入二叉树(前序遍历):\n");
TreeNode* root = createTree();
printf("前序遍历结果为:\n");
preorderTraverse(root);
printf("\n");
printf("叶子结点为:\n");
printLeafNode(root);
printf("\n");
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)