用C语言写出要求按照先序遍历的顺序输出给定二叉树的叶结点,并且你给出一个二叉树代入程序中
时间: 2023-06-14 10:05:35 浏览: 117
用C语言求二叉树叶子结点
4星 · 用户满意度95%
以下是用C语言实现先序遍历输出二叉树叶子节点的代码,假设二叉树的叶子节点存储为0:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void preorder(struct TreeNode *root) {
if (root == NULL) {
return;
}
if (root->left == NULL && root->right == NULL) {
printf("%d ", root->val);
}
preorder(root->left);
preorder(root->right);
}
int main() {
struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->left->left = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->left->left->val = 0;
root->left->right = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->left->right->val = 0;
root->right = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->right->left = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->right->left->val = 4;
root->right->right = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->right->right->val = 5;
root->right->right->left = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->right->right->left->val = 0;
root->right->right->right = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->right->right->right->val = 0;
preorder(root);
return 0;
}
```
上述代码中先定义了一个二叉树的结构体,包含节点的值和左右子节点的指针,然后通过先序遍历的方式遍历整个二叉树,当遇到叶子节点时输出其值即可。最后在main函数中创建了一个二叉树并调用preorder函数进行遍历输出。
阅读全文