二叉树的建立与遍历代码C语言
时间: 2023-11-05 16:11:00 浏览: 78
创建二叉树的C语言代码
```
#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;
}
struct node* create_binary_tree() {
int data;
struct node* root = NULL;
printf("Enter data (0 for no node):");
scanf("%d", &data);
if (data == 0) {
return NULL;
}
root = create_node(data);
printf("Enter left child of %d:\n", data);
root->left = create_binary_tree();
printf("Enter right child of %d:\n", data);
root->right = create_binary_tree();
return root;
}
void inorder_traversal(struct node* root) {
if (root == NULL) {
return;
}
inorder_traversal(root->left);
printf("%d ", root->data);
inorder_traversal(root->right);
}
int main() {
struct node* root;
root = create_binary_tree();
printf("Inorder traversal of binary tree is: ");
inorder_traversal(root);
return 0;
}
```
这段代码包括了创建二叉树并中序遍历的函数。您可以运行此代码并输入适当的输入以创建二叉树。输出将是中序遍历的结果。
希望这对您有所帮助!
阅读全文