问题描述:
假设二叉数的数据元素为字符,采用二叉链式存储结构。请编码实现二叉树ADT,其中包括创建二叉树、遍历二叉树(深度、广度)、求二叉树的深度(高度)、计算二叉树的元素个数、计算二叉树的叶子数、二叉树的格式输出等。
根据输入的符号,执行相应的操作。如下:
C:创建二叉树,创建成功输出 “Created success!”。要求实现两种创建算法。输入数字“1" ,是根据完全前序序列创建二叉树,#表示空结点(空子树);下一行输入二叉树的完全前序序列。 输入数字“2”,是根据二叉树的前序和中序序列创建二叉树,后面有三行,分别输入元素个数、前序序列和中序序列。
H:求二叉树的高度; 输出: Height=高度
L:计算二叉树的叶子数;输出:Leaves=叶子个数
N:计算二叉树中元素总个数;输出:Nodes=结点个数
1:先序遍历二叉树;输出:Preorder is:序列 .
2:中序遍历二叉树;输出:Inorder is:序列 .
3:后序遍历二叉树;输出:Postorder is:序列 .
4:广度遍历二叉树;输出:BFSorder is:序列 .
F:查找值为x的结点个数;输出:The count of x is 个数 .
P:以目录缩格文本形式输出所有节点。输出:The tree is:(换行,下面各行是输出的二叉树)
X:退出
例如:
输入 | Result |
---|---|
C 1 ABC##DE#G##F### H L N 1 2 3 4 F A P X |
Created success! Height=5 Leaves=3 Nodes=7 Preorder is:A B C D E G F . Inorder is:C B E G D F A . Postorder is:C G E F D B A . BFSorder is:A B C D E F G . The count of A is 1 The tree is: A B C D E G F |
答案:
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
int cnt = 0;
typedef struct BinTreeNode{
struct BinTreeNode *leftChild,*rightChild;
char data;
}BNode,*BTree;
void CreateBinTree1(BTree &subTree){
char item;
cin>>item;
if(item!='#') {
subTree = new BNode();
subTree->data = item;
CreateBinTree1(subTree->leftChild);
CreateBinTree1(subTree->rightChild);
}
else subTree = NULL;
}
BTree CreateBinTree2(char *VLR,char *LVR,int n){
if (n==0) return NULL;
int k = 0;
while (VLR[0]!=LVR[k]) k++;
BTree temp = new BNode();
temp->data = VLR[0];
temp->leftChild = CreateBinTree2(VLR+1,LVR