用c语言完成一个二叉树的先序遍历
时间: 2024-05-12 11:13:49 浏览: 69
下面是用C语言实现二叉树的先序遍历的代码:
```c
#include<stdio.h>
#include<stdlib.h>
//定义二叉树节点结构体
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
//创建二叉树节点
struct TreeNode* createNode(int val) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
//先序遍历函数
void preorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val); //访问节点
preorderTraversal(root->left); //递归遍历左子树
preorderTraversal(root->right); //递归遍历右子树
}
int main() {
//创建二叉树
struct TreeNode* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
//先序遍历二叉树
printf("The preorder traversal of the binary tree is: ");
preorderTraversal(root);
return 0;
}
```
输出结果为:
```
The preorder traversal of the binary tree is: 1 2 4 5 3 6 7
```
阅读全文