设计算法按前序次序打印二叉树中的叶子结点。 C语言
时间: 2023-06-12 19:03:04 浏览: 110
以下是一个基于递归的算法实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 创建二叉树
TreeNode* createTree() {
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->val = 5;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 6;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 7;
return root;
}
// 前序遍历打印二叉树中的叶子节点
void printLeaves(TreeNode* root) {
if (root == NULL) {
return;
}
if (root->left == NULL && root->right == NULL) {
printf("%d ", root->val);
}
printLeaves(root->left);
printLeaves(root->right);
}
int main() {
TreeNode* root = createTree();
printLeaves(root);
return 0;
}
```
注意,这里的二叉树是写死的,实际应用中需要根据具体需求动态创建二叉树。
阅读全文