数据结构实验之二叉树的建立与遍历
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem 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
这道题的新点在于深度的判断(此处转载自百度)
先遍历二叉树的左子树的深度,然后再遍历二叉树右子树的深度。最后判断左子树和右子树的深度,如果左子树比右子树深则返回左子树深度+1,否则返回右子树深度+1。
/* 初始条件: 二叉树T存在。操作结果: 返回T的深度 */
int BiTreeDepth(BiTree T)
{
int i,j;
if(!T)
return 0;
if(T->lchild)
i=BiTreeDepth(T->lchild); // 左子树深度
else
i=0;
if(T->rchild)
j=BiTreeDepth(T->rchild); // 右子树深度
else
j=0;
return i>j?i+1:j+1;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct TreeNode *BinTree;
typedef char ElementType;
typedef BinTree Position;
struct TreeNode
{
ElementType Data;
BinTree Left;
BinTree Right;
} ;
char st[55];
int cnt;
struct TreeNode *creat()
{
struct TreeNode *root;
if(st[++cnt] == ',')
{
root = NULL;
}
else
{
root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->Data = st[cnt];
root->Left = creat();
root->Right = creat();
}
return root;
};
void zhongxu(struct TreeNode *root)
{
if(root)
{
zhongxu(root->Left);
printf("%c",root->Data);
zhongxu(root->Right);
}
}
void houxu(struct TreeNode *root)
{
if(root)
{
houxu(root->Left);
houxu(root->Right);
printf("%c",root->Data);
}
}
int leave(struct TreeNode *root)
{
if(root == NULL)
return 0;
if(root->Left == NULL&& root->Right == NULL)
return 1;
else return leave(root->Left) + leave(root -> Right);
}
int depth(struct TreeNode *root) //深度的判断
{
int i,j;
if(!root)return 0;
if(root->Left) i= depth(root->Left);
else i = 0;
if(root->Right)j = depth(root->Right);
else j = 0;
return i>j?i + 1:j+1;
}
int main()
{
while(~scanf("%s",st))
{
cnt = -1;
struct TreeNode *root;
root = creat();
zhongxu(root);
printf("\n");
houxu(root);
printf("\n");
printf("%d\n",leave(root));
printf("%d\n",depth(root));
}
return 0;
}