#include<stdio.h>
#include<stdlib.h>
typedef struct bitnode
{
char data;
struct bitnode *lchild,*rchild;
}bitnode,*bitree;//二叉树节点类型和节点指针类型
bitree create()//先序创建
{
bitree root=NULL;
char c;
scanf("%c",&c);
fflush(stdin);
if(c=='#')return NULL;
else
{
root=(bitnode*)malloc(sizeof(bitnode));
root->data=c;
root->lchild=create();
root->rchild=create();
}
return root;
}
void preorder(bitree root)//先根遍历
{
if(!root)return;
else
{
putchar(root->data);
preorder(root->lchild);
preorder(root->rchild);
}
}
void inorder(bitree root)//中根遍历
{
if(!root)return;
else
{
inorder(root->lchild);
putchar(root->data);
inorder(root->rchild);
}
}
void postorder(bitree root)//后根遍历
{
if(!root)return;
else
{
postorder(root->lchild);
postorder(root->rchild);
putchar(root->data);
}
}
int leafcount(bitree root)//计算叶子节点
{
if(!root)return 0;
else
{
if(!root->lchild&&!root->rchild)return 1;
else return leafcount(root->lchild)+leafcount(root->rchild);
}
}
int depth(bitree root)//树的高度
{
if(!root)return 0;
else
{
int m=depth(root->lchild);
int n=depth(root->rchild);
return (m>n?m:n)+1;
}
}
void Revolute(bitree root)// 交换左右子树
{
bitree t;
t=root->lchild;
root->lchild=root->rchild;
root->rchild=t;
if(root->lchild)Revolute(root->lchild);
if(root->rchild)Revolute(root->rchild);
}
void main()
{
bitree root=NULL;
printf("输入先序序列:\n");
root=create();
printf("前序遍历:\n");
preorder(root);
printf("\n");
printf("中序遍历:\n");
inorder(root);
printf("\n");
printf("后序遍历:\n");
postorder(root);
printf("\n");
printf("二叉树的叶子结点个数为:%d\n",leafcount(root));
printf("二叉树的高度为:%d\n",depth(root));
printf("交换左右子树后\n");
Revolute(root);
printf("前序遍历:\n");
preorder(root);
printf("\n");
printf("中序遍历:\n");
inorder(root);
printf("\n");
printf("后序遍历:\n");
postorder(root);
printf("\n");
}
/*输入序列为前序序列,#代表空
例如二叉树为
--------a
-------/-\
------b---c
-----/-\
----d---e
输入abd##e##c##(每次输入一个字符回车)*/
分享到:
相关推荐
非递归前序,中序,后序遍历二叉树(优化算法)
用c语言写的遍历二叉树 包括前序,中序,后序
二叉树先序、中序、后序遍历非递归算法,简述了二叉树的基本算法。
二叉树的递归遍历算法非常好写。这个.cpp文件里是二叉树的非递归遍历!
用C++写的二叉树先序遍历、中序遍历和后序遍历非递归算法
二叉树的基本操作,包括前序、中序、后序遍历的递归和非递归算法,不得不下的资源
二叉树的遍历,全部用递归实现,很有规律! 二叉树的遍历,全部用递归实现,很有规律
一个实现二叉树遍历的程序代码,有先序,中序和后序。
C语言实现通用栈结构 递归遍历二叉树 非递归遍历二叉树 (前,中,后序) exmaple.c为测试文件
C语言实现二叉树的前序、中序、后续遍历(递归法),大家可以看看哈。。。
用C语言实现数据结构中二叉树的前序中序后序遍历 int main()//主函数部分 { BiTree T=NULL; int Layer=0; int LayerT=0; printf("请输入二叉树:\n"); CreatBiTree(&T);printf("你输入的二叉树为:(竖型树状...
java实现 二叉树的遍历 前序遍历用到递归, 中序和后序遍历用到栈, 其实还是有一定难度的
二叉树前序、中序、后序三种遍历的非递归算法(C语言)
常见的二叉树遍历,分为前序、中序、后续和层次遍历4种。 层次遍历相对比较好理解,对于前3种遍历方式概念的记忆方式应该是这样的:左和右的顺序始终是固定的—先左后右,所谓的前序、中序和后序是针对根来说的。...
关于数据结构实验的二叉树问题
二叉树前序,中序,后序,求深度的递归和非递归方法
二叉树先序、中序、后序三种遍历的非递归算法
二叉树的递归遍历,中序遍历,先序遍历,后序遍历,通过学习二叉树的遍历,可以让我们更紧一步掌握数据的遍历
关于二叉树前序和后序的非递归遍历算法.rar
自己编写的实验二叉树的后序遍历非递归算法 包括以递归中序遍历建立二叉树 前序,中序,后序递归以及非递归实现二叉树的遍历 经vc6.0编译通过 自己实验,不足之处应该很多,望指出