二叉树的遍历
来源:互联网 发布:淘宝模板装修市场 编辑:程序博客网 时间:2024/06/07 21:00
int LeftCount=0;
int depth =0;
typedef struct Node
{
char data;
struct Node *LChild;
struct Node *RChild;
}BitNode, *BiTree;
/**
*
*前序遍历树
*根左右
**/
void preOrder(BiTree root)
{
if(root!=NULL)
{
printf(“%c “, root->data);
//Visit(root->data);//访问根节点
preOrder(root->LChild);//先序遍历左子树
preOrder(root->RChild);//先序遍历右子数
}
}
/**
*
*中序遍历树
*左根右
**/
void InOrder(BiTree root)
{
if(root!=NULL)
{
preOrder(root->LChild);
//Visit(root->data);
printf(“%c “, root->data);
preOrder(root->RChild);
}
}
/**
*BiTree
*后序遍历树
*左右根
**/
void PostOrder(BiTree root)
{
if(root!=NULL)
{
PostOrder(root->LChild);
PostOrder(root->RChild);
//Visit(root->data);
printf(“%c “, root->data);
}
}
/**
*建树
*
*
**/
void CreateBiTree(BiTree *bt)
{ char ch;
ch=getchar();
if(ch==’.’)
*bt=NULL;
else
{
bt=(BiTree )malloc(sizeof(BitNode));
(*bt)->data=ch;
CreateBiTree(&((*bt)->LChild));
CreateBiTree(&((*bt)->RChild));
}
}
BiTree CreateTree()
{
BiTree root;
int ch;
scanf(“%c”, &ch);
if(ch ==’.’)
{
root = NULL;
}
else
{
root = (BitNode *)malloc(sizeof(BitNode));
if(root == NULL)
{
//printf(stderr, “malloc() error in CreateTree.\n”);
return;
}
root->data = ch; //生成根结点 root->LChild = CreateTree(root->LChild); //构造左子树 root->RChild = CreateTree(root->RChild); //构造右子树}return root;
}
/**
*
*求树的高度
*
**/
int PostTreeDepth(BiTree bt) /* 后序遍历求二叉树bt高度的递归算法 */
{
int hl, hr, max;
if(bt!=NULL)
{
hl=PostTreeDepth(bt->LChild); /* 求左子树的深度 */
hr=PostTreeDepth(bt->RChild); /* 求右子树的深度 */
max=hl>hr?hl:hr; /* 得到左、右子树深度较大者*/
return(max+1); /* 返回树的深度 */
}
else return(0); /* 如果是空树,则返回0 */
}
/**
*
*统计叶子节点数
**/
int leaf(BiTree root)
{
int LeafCount;
if(root==NULL)
LeafCount =0;
else if ((root->LChild==NULL)&&(root->RChild==NULL))
LeafCount =1;
else /* 叶子数为左右子树的叶子数目之和 */
LeafCount =leaf(root->LChild)+leaf(root->RChild);
return LeafCount;
}
int main()
{
BiTree root;
CreateBiTree(&root);
//BiTree bt= CreateTree(); //preOrder(bt); printf("先序遍历\n");preOrder(root);//先序 printf("后序序遍历\n");PostOrder(root);//后序 printf("中序遍历\n");InOrder(root);//中序printf("\n叶子数:%d\n",leaf(root));printf("\n树高度:%d\n",PostTreeDepth(root));
}
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 快速排序法一(C)
- jQuery Validate
- 面向对象技术与方法作业
- Spring Cloud Eureka 初探
- 门罗币linux钱包
- 二叉树的遍历
- 【Spring Cloud】Zuul 路由访问
- c++primer第五版 练习5.21
- Arduino--基础(五)--DHT11模块的使用
- 学习笔记04(MySQL数据库做用户登陆)
- BP算法纯理论推导
- 欢迎使用CSDN-markdown编辑器
- SSL--VPN未分配虚拟ip地址问题
- unity基础,控制游戏目标