二叉树创建
效果
![](https://i-blog.csdnimg.cn/blog_migrate/7afc3f8c6542d98adb66e44d8277fddf.png)
创建二叉树代码
//二叉树的创建
int Tree_create(tree* T)
{
char value;
printf("please input char : ");
scanf("%c",&value);
getchar();
if(value=='#')
{
*T=NULL;
return 0;
}
tree newsnode=Tree_node(value);
*T=newsnode;
Tree_create(&(*T)->left);
Tree_create(&(*T)->right);
}
//节点的创建
tree Tree_node(data_t value)
{
tree newsnode=(tree)malloc(sizeof(struct Node));
if(newsnode==NULL)
{
printf("malloc fail\n");
return NULL;
}
newsnode->val=value;
newsnode->left=NULL;
newsnode->right=NULL;
return newsnode;
}
所有代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef char data_t;
typedef struct Node
{
data_t val;
struct Node* left;
struct Node* right;
}*tree;
//二叉树的创建
int Tree_create(tree* T);
//节点的创建
tree Tree_node(data_t value);
//二叉树的先序遍历
int Tree_front_show(tree T);
//二叉树的中序遍历
int Tree_middle_show(tree T);
//二叉树的后序遍历
int Tree_back_show(tree T);
//二叉树的释放
int Tree_free(tree* T);
int main(int argc, const char *argv[])
{
tree T=NULL;
Tree_create(&T);
Tree_front_show(T);
puts("");
Tree_middle_show(T);
puts("");
Tree_back_show(T);
puts("");
Tree_free(&T);
Tree_front_show(T);
puts("");
return 0;
}
//二叉树的创建
int Tree_create(tree* T)
{
char value;
printf("please input char : ");
scanf("%c",&value);
getchar();
if(value=='#')
{
*T=NULL;
return 0;
}
tree newsnode=Tree_node(value);
*T=newsnode;
Tree_create(&(*T)->left);
Tree_create(&(*T)->right);
}
//节点的创建
tree Tree_node(data_t value)
{
tree newsnode=(tree)malloc(sizeof(struct Node));
if(newsnode==NULL)
{
printf("malloc fail\n");
return NULL;
}
newsnode->val=value;
newsnode->left=NULL;
newsnode->right=NULL;
return newsnode;
}
//二叉树的先序遍历
int Tree_front_show(tree T)
{
if(T==NULL)
return 0;
printf("%c ",T->val);
Tree_front_show(T->left);
Tree_front_show(T->right);
}
//二叉树的中序遍历
int Tree_middle_show(tree T)
{
if(T==NULL)
return 0;
Tree_middle_show(T->left);
printf("%c ",T->val);
Tree_middle_show(T->right);
}
//二叉树的后序遍历
int Tree_back_show(tree T)
{
if(T==NULL)
return 0;
Tree_back_show(T->left);
Tree_back_show(T->right);
printf("%c ",T->val);
}
//二叉树的释放
int Tree_free(tree* T)
{
if(*T==NULL)
return 0;
Tree_free(&(*T)->left);
Tree_free(&(*T)->right);
free(*T);
*T=NULL;
}