C语言实现二叉树

这是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;
}


在创建二叉树 时我们先创建它的根结点,然后再创建左结点,当左结点返回为空的时候,我们再创建右结点,这是有递归实现的。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值