#include<bits/stdc++.h>
const int Maxsize = 101;
typedef double elementType;
struct TreeNode_SM {
elementType value;
bool isEmpty;
};
TreeNode_SM Tree[Maxsize];
int Judge = 0;
int highLength = 0;
int nodeValue = 0;
int nodeX = -10000;
int nodeY = 0;
bool initTree(TreeNode_SM *Tree) {
for (int i = 0; i < Maxsize; i++) {
Tree[i].isEmpty = true;
Tree[i].value = 0;
}
}
void makeTree(TreeNode_SM *Tree, int *highLength) {
std::cout << "然后每次输入三个数值:"
"层数(行数)、"
"此层第几个(列数(自左至右))、"
"该结点的值、"
"\n***若输入层数为-1结束***\n";
while (nodeX != -1) {
std::cin >> nodeX;
std::cin >> nodeY;
std::cin >> nodeValue;
if (nodeX > *highLength) {
std::cout << "!!!输入非法!!!";
}
if (nodeX != -1) {
if (nodeY > pow(2.0, (double) (nodeX - 1)) || nodeY <= 0) {
std::cout << "!!!输入非法!!!";
}
Tree[(int) pow(2.0, (double) (nodeX - 1)) - 1 + nodeY].value = nodeValue;
Tree[(int) pow(2.0, (double) (nodeX - 1)) - 1 + nodeY].isEmpty = false;
}
else {
break;
}
}
}
void show(TreeNode_SM *Tree,int *highLength) {
if ((*highLength) > 0){
for(int i = 1 ; i <= (int)pow(2.0,(double)((*highLength))) - 1; i++){
if(!Tree[i].isEmpty){
std::cout << "index: " << i << "; value:"<< Tree[i].value << "\t";
}
}
std::cout << std::endl;
}
else{
std::cout << "!!!空!!!\n";
}
}
void test() {
initTree(Tree);
while (true) {
std::cout << "********************1、层序输入构造二叉树********************\n";
std::cout << "********************2、退出********************\n";
std::cin >> Judge;
switch (Judge) {
case 1: {
std::cout << "输入二叉树的层数:\n";
std::cin >> highLength;
makeTree(Tree,&highLength);
std::cout << "显示该二叉树:\n";
show(Tree,&highLength);
nodeX = -10000;
break;
}
case 2: {
return;
}
default: {
std::cout << "!!!输入非法!!!";
break;
}
}
}
}
int main() {
test();
}
E:\CODING__ALAN_CF\cmake-build-debug\binaryTree_SMeomory.exe
********************1、层序输入构造二叉树********************
********************2、退出********************
1
输入二叉树的层数:
4
然后每次输入三个数值:层数(行数)、此层第几个(列数(自左至右))、该结点的值、
***若输入层数为-1结束***
1 1 1
2 1 2
2 2 3
3 2 4
3 4 5
4 3 6
-1 -1 -1
显示该二叉树:
index: 1; value:1 index: 2; value:2 index: 3; value:3 index: 5; value:4 index: 7; value:5
index: 10; value:6
********************1、层序输入构造二叉树********************
********************2、退出********************