使用c语言编写前序遍历二叉树
时间: 2024-01-23 07:55:17 浏览: 65
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *create_node(int data)
{
struct node *new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
void preorder(struct node *root)
{
if(root != NULL)
{
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
}
int main()
{
struct node *root = create_node(1);
root->left = create_node(2);
root->right = create_node(3);
root->left->left = create_node(4);
root->left->right = create_node(5);
printf("Preorder traversal of binary tree is: ");
preorder(root);
return 0;
}
阅读全文