从键盘输入二叉树的元素,建立二叉树,实现二叉树的先序,中序,后序遍历算法。用c语言实现
时间: 2023-07-28 07:19:00 浏览: 106
好的,以下是实现您要求的代码:
```
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *left;
struct node *right;
} Node;
Node* create_tree(){
int x;
scanf("%d", &x);
if(x == -1){
return NULL;
}
Node *root = (Node*) malloc(sizeof(Node));
root->data = x;
root->left = create_tree();
root->right = create_tree();
return root;
}
void preorder(Node *root){
if(root == NULL){
return;
}
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
void inorder(Node *root){
if(root == NULL){
return;
}
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
void postorder(Node *root){
if(root == NULL){
return;
}
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
int main(){
printf("请输入二叉树的元素,-1表示空节点:\n");
Node *root = create_tree();
printf("先序遍历结果为:");
preorder(root);
printf("\n中序遍历结果为:");
inorder(root);
printf("\n后序遍历结果为:");
postorder(root);
printf("\n");
return 0;
}
```
代码中,`create_tree()`函数用于创建二叉树,`preorder()`、`inorder()`和`postorder()`分别用于实现先序、中序和后序遍历。在`main()`函数中,先输入二叉树元素,然后调用相应的遍历函数输出遍历结果。
阅读全文