已知二叉树的完全前序序列可以唯一确定一棵二叉树。现给出二叉树的完全前序序列,使用C或C++编写算法完成:
(1) 以二叉链表为存储结构,建立二叉树;
(2) 编写先序遍历算法,输出先序遍历序列;
(3) 编写中序遍历算法,输出中序遍历序列;
(4) 编写后序遍历算法,输出后序遍历序列;
(5) 编写层序遍历算法,输出层序遍历序列,要求按层输出,每层输出一行;
(6) 编写算法,计算并输出二叉树的叶子数;
(7) 编写算法,计算并输出二叉树的高度。
输入格式:
二叉树数据元素为单个字符且各不相同,取值范围为A~Z,a~z,二叉树不为空。输入数据分为2行,第1行为二叉树完全前序序列字符(包括#)个数,第2行为二叉树的完全前序序列。例如,上面二叉树的输入为:ABD##FE###CG#H##I##,其中#代表为空的位置。
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef char telem;
int n,i;
char a[100];
int cnt=0;
typedef struct BTNode
{
telem data;
struct BTNode *left;
struct BTNode *right;
} Node;
Node* createBT()
{
Node *p;
telem ch;
ch=a[cnt];
if(ch=='#')
{
p=NULL;
cnt++;
}
else
{
cnt++;
p=(Node*)malloc(sizeof(Node));
p->data = ch;
p->left = createBT();
p->right = createBT();
}
return p;
}
void xianxu(Node* root)
{
if(root)
{
cout<< root->data;
xianxu(root->left);
xianxu(root->right);
}
}
void zhongxu(Node* root)
{
if(root)
{
zhongxu(root->left);
cout << root->data;
zhongxu(root->right);
}
}
void houxu(Node* root)
{
if(root)
{
houxu(root->left);
houxu(root->right);
cout << root->data;
}
}
int yezijiedianshu(Node* root)
{
if(!root)
{
return 0;
}
else if((root->left == NULL)&&(root->right == NULL))
{
return 1;
}
else
{
return yezijiedianshu(root->left)+yezijiedianshu(root->right);
}
}
int gaodu(Node* root)
{
if(root)
{
return gaodu(root->left)>gaodu(root->right)?gaodu(root->left)+1:gaodu(root->right)+1;
}
if(root == NULL)
{
return 0;
}
}
int main()
{
cin >>n;
for(i=0; i<n; i++)
{
cin >>a[i];
}
Node *root=NULL;
root = createBT();
cout <<"preorder traversal:";
xianxu(root);
cout <<endl;
cout <<"inorder traversal:";
zhongxu(root);
cout <<endl;
cout <<"postorder traversal:";
houxu(root);
cout <<endl;
cout <<yezijiedianshu(root)<<endl;
cout <<gaodu(root)<<endl;
return 0;
}