您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之 二叉树的建立与遍历

2013-07-01 13:37 459 查看
题目:http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=2136&cid=1184



#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>

using namespace std;

int sum=0;
struct tree *p;
struct tree
{
char data;
struct tree *l,*r;
};

struct tree* build(struct tree *p)//建树
{
char c;
c=getchar();
p=(struct tree*)malloc(sizeof(struct tree));

if(c==',')
p=NULL;
else
{
p->data=c;
p->l=build(p->l);
p->r=build(p->r);
}
return p;
};

void inorder(struct tree *p)//中序遍历
{
if(p)
{
inorder(p->l);
printf("%c",p->data);
inorder(p->r);
}
};

void postorder(struct tree *p)//后序遍历
{
if(p)
{
postorder(p->l);
postorder(p->r);
printf("%c",p->data);
}
};

int leaf(struct tree *p)//叶子个数
{
if(p)
{
if(p->l==NULL&&p->r==NULL)
sum++;
leaf(p->l);
leaf(p->r);
}
return sum;
};

int deep(struct tree *p)//树的深度
{
int left,right;
if(!p) return 0;
else
{
left=deep(p->l);
right=deep(p->r);
return 1+(left>right?left:right);//取左右子树深度的最大值加一返回
}
return 1;
};

int main()
{
struct tree *root;
root=build(p);
inorder(root);
printf("\n");
postorder(root);
printf("\n");
sum=leaf(root);
printf("%d\n",sum);
printf("%d\n",deep(root));
}


其他操作:

int CountNode(BiTree T) //统计二叉树的节点个数

{

if(!T)

return 0;

else

return 1+CountNode(T->lchild)+CountNode(T->rchild);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: