语言 c:创建二叉树、前序遍历、中间遍历、后续遍历
最编程
2024-10-09 07:04:28
...
#include <stdio.h>
#include <stdlib.h>
typedef struct Tree{
int value;
struct Tree* lchild;
struct Tree* rchild;
} Tree;
// 创建节点
Tree* Tree_createnode(int value){
Tree* node = (Tree* )malloc(sizeof(Tree));
node->value = value;
node->lchild = NULL;
node->rchild = NULL;
return node;
}
// 创建二叉树
Tree* Tree_createtree(){
Tree* root = NULL;
char ch;
scanf("%c", &ch);
if(ch == '#') return root;
else{
root = Tree_createnode(ch - '0');
root->lchild = Tree_createtree();
root->rchild = Tree_createtree();
}
return root;
}
// 前序遍历
void Tree_preorder(Tree* root){
if(root != NULL){
printf("[%d] -> ", root->value);
Tree_preorder(root->lchild);
Tree_preorder(root->rchild);
}
}
// 中序遍历
void Tree_inorder(Tree* root){
if(root != NULL){
Tree_inorder(root->lchild);
printf("[%d] -> ", root->value);
Tree_inorder(root->rchild);
}
}
// 后序遍历
void Tree_postorder(Tree* root){
if(root != NULL){
Tree_postorder(root->lchild);
Tree_postorder(root->rchild);
printf("[%d] -> ", root->value);
}
}
int main(){
printf("创建二叉树:\n");
Tree* root = Tree_createtree();
printf("前序遍历二叉树:\n");
Tree_preorder(root);
printf("NULL\n");
printf("中序遍历二叉树:\n");
Tree_inorder(root);
printf("NULL\n");
printf("后续遍历二叉树:\n");
Tree_postorder(root);
printf("NULL\n");
return 0;
}