先序遍历 C 语言实现277
先序遍历是一种深度优先搜索算法,它以根节点为起始点,依次遍历子树的左分支和右分支。在 C 语言中,可以利用递归实现先序遍历二叉树。
算法步骤:1. 如果树为空,返回。
2. 访问根节点。
3. 先序遍历左子树。
4. 先序遍历右子树。
代码实现:```c
#include
#include
struct node {
int data;
struct node *left;
struct node *right;
};
// 先序遍历二叉树
void preorderTraversal(struct node *root) {
if (root == NULL) {
return;
}
// 访问根节点
printf("%d ", root->data);
// 先序遍历左子树
preorderTraversal(root->left);
// 先序遍历右子树
preorderTraversal(root->right);
}
int main() {
// 创建二叉树
struct node *root = (struct node *)malloc(sizeof(struct node));
root->data = 1;
root->left = (struct node *)malloc(sizeof(struct node));
root->left->data = 2;
root->left->left = (struct node *)malloc(sizeof(struct node));
root->left->left->data = 4;
root->left->right = (struct node *)malloc(sizeof(struct node));
root->left->right->data = 5;
root->right = (struct node *)malloc(sizeof(struct node));
root->right->data = 3;
root->right->left = (struct node *)malloc(sizeof(struct node));
root->right->left->data = 6;
root->right->right = (struct node *)malloc(sizeof(struct node));
root->right->right->data = 7;
// 先序遍历二叉树
preorderTraversal(root);
return 0;
}
```
输出:```
1 2 4 5 3 6 7
```
2024-11-07
下一篇:C语言函数指针调用:深入理解
极客深潜Python数据科学:解锁高效与洞察力的秘籍
https://www.shuihudhg.cn/134265.html
PHP高效传输二进制数据:深入解析Byte数组的发送与接收
https://www.shuihudhg.cn/134264.html
Python调用C/C++共享库深度解析:从ctypes到Python扩展模块
https://www.shuihudhg.cn/134263.html
深入理解与实践:Python在SAR图像去噪中的Lee滤波技术
https://www.shuihudhg.cn/134262.html
Java方法重载完全指南:提升代码可读性、灵活性与可维护性
https://www.shuihudhg.cn/134261.html
热门文章
C 语言中实现正序输出
https://www.shuihudhg.cn/2788.html
c语言选择排序算法详解
https://www.shuihudhg.cn/45804.html
C 语言函数:定义与声明
https://www.shuihudhg.cn/5703.html
C语言中的开方函数:sqrt()
https://www.shuihudhg.cn/347.html
C 语言中字符串输出的全面指南
https://www.shuihudhg.cn/4366.html