先根遍历二叉树c语言程序,二叉树先序遍历C语言实现
时间: 2024-01-07 12:02:46 浏览: 146
c实现二叉树先序层序遍历
5星 · 资源好评率100%
以下是二叉树的先序遍历C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left;
struct node *right;
};
void preorder(struct node *root) {
if (root == NULL) {
return;
}
printf("%d ", root->data);
preorder(root->left);
preorder(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 = NULL;
root->left->right = NULL;
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 = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (struct node*)malloc(sizeof(struct node));
root->right->right->data = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
printf("先序遍历结果为:");
preorder(root);
printf("\n");
return 0;
}
```
上述代码中,我们定义了一个二叉树的结构体,包含数据、左子节点和右子节点。然后,我们定义了一个先序遍历的函数,其中先访问根节点、再遍历左子树、最后遍历右子树。在主函数中,我们手动构造了一棵二叉树,并输出它的先序遍历结果。
阅读全文