您的位置:首页 > 其它

二叉树——已知二叉树先序,建树,并输出中序、后序,并求树叶数和深度

2014-08-22 12:55 225 查看
Description  已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。
Input  输入一个长度小于50个字符的字符串。Output输出共有4行: 
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。Sample Input
abc,,de,g,,f,,,
Sample Output
cbegdfa
cgefdba
3
5


#include <iostream>
#include"cstdio"
#include"cstring"
#include"cstdlib"
using namespace std;
struct tree//定义一个结构体来进行存放各结点的信息以及其左右孩子的位置——用链表进行存储
{
tree*l;
tree*r;
char data;
};
tree*TREE(tree*p)//输入进各结点并建树
{
char q;
scanf("%c",&q);
if(q==',')//某条支路结束标志
p=NULL;
else
{
p=(tree*)malloc(sizeof(tree));
p->data=q;
p->l=TREE(p);
p->r=TREE(p);
}
return p;
}
void zhong(tree*p)//用递归来进行寻找输出
{
if(p!=NULL)
{
zhong(p->l);
printf("%c",p->data);//左结点为NULL,输出此时的结点信息data
zhong(p->r);//继续从右子树进行寻找
}
}
void hou(tree*p)
{
if(p!=NULL)
{
hou(p->l);
hou(p->r);
printf("%c",p->data);//只有当左右子树都为NULL时,输出此结点信息
}
}
int sum=0;
int node(tree*p)
{
if(p!=NULL)
{
node(p->l);
node(p->r);
if((p->l==NULL)&&(p->r==NULL))//一直寻找到树叶时,计数加1
sum++;
}
return sum;
}

int deep(tree*p)//先从根结点往左右子树找,不断寻找到树叶,然后从树叶往回一层层加1,一直到根结点
{
int dl,dr;
if(p==NULL)return 0;//碰到NULL时返回
dl=deep(p->l);//计算左子树深度
dr=deep(p->r);//计算右子树深度
dl=dl>dr?dl+1:dr+1;//比较左右子树此时深度,取最大的加上此结点的深度,即加1
return dl;
}
int main()
{
tree *root;
root=(tree*)malloc(sizeof(tree));
root=TREE(root);
zhong(root);
putchar('\n');
hou(root);
putchar('\n');
printf("%d\n",node(root));
printf("%d\n",deep(root));
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐