//head.h #include<string> const int Maxsize = 32; struct information { int value; int exist; }; class Sequential_Storage_Tree { public: Sequential_Storage_Tree() { memset(tree, 0, sizeof(information)*Maxsize); count = 0; } void Set(); void Sequence(); void Print(); void Codyledon(); private: information tree[Maxsize]; int count; };
#include"head.h" #include<iostream> using namespace std; void Sequential_Storage_Tree::Set() { if (count > Maxsize) throw "overflow"; cout << "enter a data and a location : "; int data,location; cin >> data>>location; if (location > Maxsize) throw "wrong location"; if (tree[location].exist != 0) throw "you will coveer the origin"; else { tree[location].value = data; count++; tree[location].exist = 1; } } void Sequential_Storage_Tree::Sequence() {for(int i=1;i<=Maxsize;i++) { if (tree[i].exist != 0) cout << "the data in " << i<< " is " << tree[i].value<<endl; } } void Sequential_Storage_Tree::Print() { for (int i = 1; i<=Maxsize; i++) { if (tree[i].exist != 0) { cout << "the data in " << i << " is " << tree[i].value << endl; if (i > 1 && tree[i / 2].exist != 0) cout << "the parent are" << i / 2<<endl; if (2 * i <= count&&tree[2 * i].exist != 0) cout << "the left child are" << 2*i<<endl; if (2 * i + 1<= count&&tree[2 * i + 1].exist != 0) cout << "the right child are" << 2 * i+1<<endl; } } } void Sequential_Storage_Tree::Codyledon() { cout << "the Codyledon have :"; int tally = 0; for (int i = 1; i <= Maxsize; i++) { if (tree[i].exist != 0) tally++; if (tree[i].exist!=0&&tree[2 * i].exist == 0 && tree[2 * i + 1].exist == 0) cout << i<<" "; if (tally >= count) break; } }
#include<iostream> #include"head.h" int main() { Sequential_Storage_Tree binary; std::cout << "MENU"; int use = 0; while (use != 5) { std::cout << "\n1.SET\n2.Sequence\n3.Print\n4.Codyledon\n5.Exit\nNow input a number to use function:"; std::cin >> use; switch (use) { case 1:binary.Set(); break; case 2:binary.Sequence(); break; case 3:binary.Print(); break; case 4:binary.Codyledon(); break; default: break; } } return 0; }算法空间储存效率:1/2