C语言实现二叉树

来源:互联网 发布:java编写99乘法表题目 编辑:程序博客网 时间:2024/05/21 19:50
这是lz的第一篇博客,欢迎大家的到来!
现在进入正题,熟悉算法的应该都听说过二叉树,这篇文章可供不理解二叉树的人学习。
好啦,直接贴代码。。。
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>




typedef struct node //定义一个树的结点
{
char data;
struct node *left;
struct node *right;
}Node;




Node* create() //创建一颗二叉树
{
char ch;
Node *tree;
scanf("%c",&ch);
if(ch=='#')
return NULL;
else
{
tree=(Node*)malloc(sizeof(Node));
tree->data=ch;
tree->left=create();
tree->right=create();
return tree;
}
}




void preorder(Node *root) //先序进行遍历
{
if(root!=NULL)
{
printf("%c",root->data);
preorder(root->left);
preorder(root->right);
}
}




void inorder(Node *root) //中序进行遍历
{
if(root!=NULL)
{
inorder(root->left);
printf("%c",root->data);
inorder(root->right);
}
}




void endorder(Node *root) //这里就是后序遍历了
{
if(root!=NULL)
{
endorder(root->right);
printf("%c",root->data);
endorder(root->left);
}
}








int main()
{
Node *p;
p=create();
preorder(p);
printf("\n");
inorder(p);
printf("\n");
endorder(p);
printf("\n");
return 0;
}


在创建二叉树 时我们先创建它的根结点,然后再创建左结点,当左结点返回为空的时候,我们再创建右结点,这是有递归实现的。