数据结构实验之二叉树的建立与遍历
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。
Input
输入一个长度小于50个字符的字符串。
Output
输出共有4行:
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
Example Input
abc,,de,g,,f,,,
Example Output
cbegdfa
cgefdba
3
5
Hint
#include <bits/stdc++.h>
using namespace std;
int flag;
char str[55];
typedef struct node
{
char data;
struct node*left;
struct node*right;
} tree;
tree*creat(tree*root)
{
if(str[flag]==',')
{
flag++;
return NULL;
}
else
{
root=(tree*)malloc(sizeof(tree));
root->data=str[flag++];
root->left=creat(root->left);
root->right=creat(root->right);
}
return root;
}
void mid(tree*root)
{
if(root)
{
mid(root->left);
printf("%c",root->data);
mid(root->right);
}
}
void last(tree*root)
{
if(root)
{
last(root->left);
last(root->right);
printf("%c",root->data);
}
}
int leaf(tree*root)
{
if(root==NULL)
{
return 0;
}
else if(root->left==NULL&&root->right==NULL)
{
return 1;//注意只有根时返回值为1
}
else//计算左右子树叶子树加和并返回
{
int n1=leaf(root->left);
int n2=leaf(root->right);
return n1+n2;///返回两子树的叶子和
}
}
int depth(tree*root)//计算左右子树深度并返回其中的较大值
{
if(root==NULL)
{
return 0;
}
int n1=depth(root->left);
int n2=depth(root->right);
return n1>n2?n1+1:n2+1;
//如果一颗树只有一个节点,它的深度是1
//如果根节点只有左子树而没有右子树,那么二叉树的深度应该是其左子树的深度加1
//如果根节点只有右子树而没有左子树,那么二叉树的深度应该是其右树的深度加1
//如果根节点既有左子树又有右子树,那么二叉树的深度应该是其左右子树的深度较大值加1
}
int main()
{
int x,d;
tree*root=NULL;
scanf("%s",str);
flag=0;
root=creat(root);
mid(root);
printf("\n");
last(root);
printf("\n");
x=leaf(root);
printf("%d\n",x);
d=depth(root);
printf("%d\n",d);
return 0;
}