二叉树的建立及凹入表打印
先序递归建立二叉树
班级2012211313
姓名:胡卓 学号:2012211468
姓名:郭志刚 学号:2012211475
分工情况:
郭志刚BiTree CreateBiTree(BiTree& T)//先序递归创建二叉树 int main() 胡卓 void Print(BiTree& T,int t) int LEAF(BiTree& T)//计算叶子节点
完成日期:2013-11-6
问题描述:
1)用先序递归过程建立二叉树 (存储结构:二叉链表)
输入数据按先序遍历所得序列输入,当某结点左子树或右子树为空时,输入‘*’号,如输入abc**d**e**得到的二叉树为:
e
a d
b
c
(选做:由二叉树的先序序列和中序序列建立一棵二叉树。)
2)编写递归算法,计算二叉树中叶子结点的数目。
3)按凹入表方式输出该二叉树。
算法思想:
定义二叉树的数据结构类型
typedef struct BiTNode//
{
char data;
struct BiTNode*lchild,*rchild;//左右子树
}BiTNode,*BiTree;
1.先序递归创建二叉树
BiTree CreateBiTree(BiTree& T)
{
T=(BiTree)malloc(sizeof(BiTNode));
T->data='\0';
char ch;
scanf("%c",&ch);
if(ch!='*')
{
T->data=ch;
T->lchild=CreateBiTree(T->lchild);
T->rchild=CreateBiTree(T->rchild);
}
else if(ch=='*')
return NULL;
if((T->lchild==NULL&&T->rchild==NULL)||(T->lchild==NULL&&T->rchild->data!='\0')||(T->lchild->data!='\0'&&T->rchild==NULL)||(T->lchild->data!='\0'&&T->rchild->data!='\0'))
return T;
}
计算叶子节点
int LEAF(BiTree& T)
{
if(T->lchild==NULL&&T->rchild==NULL)
return 1;
else if(T->lchild==NULL&&T->rchild->data!='\0')
return LEAF(T->rchild);
else if(T->lchild->data!='\0'&&T->rchild==NULL)
return LEAF(T->lchild);
else
return (LEAF(T->lchild)+LEAF(T->rchild));
}
3.凹入表打印二叉树
void Print(BiTree& T,int t)
{
int i;
if(T)
{
Print(T->rchild,t+5);
for(i=0;i
{
printf(" ");
}
printf("%5c\n",T->data);
Print(T->lchild,t+5);
}
}
4.主函数
int main()
{
BiTree T;
printf("*******************************************\n");
printf("****************欢迎打印二叉树*************\n");
printf("*******************************************\n");
printf("请按先序遍历所得数据输入(当某节点是叶子节点时用'*'表示):\n")