Professional Documents
Culture Documents
#include <string>
#include <stdio.h>
using namespace std;
struct Student {
int id;
int age;
string name;
};
struct treeNode {
Student data;
treeNode* leftChild;
treeNode* rightChild;
};
class BSTree {
public:
BSTree();
~BSTree();
void addNode(Student& std);
void deleteNode(int id);
void search(int id);
void displayPreorder();
void displayInorder();
void displayPostorder();
private:
// utility functions
treeNode* makeEmpty(treeNode* t);
treeNode* deleteNode(int id, treeNode* t);
treeNode* findMin(treeNode* t);
treeNode* findMax(treeNode* t);
treeNode* find(treeNode* t, int id);
void preorder(treeNode* t);
void inorder(treeNode* t);
void postorder(treeNode* t);
treeNode* root;
};
// constructor
BSTree::BSTree() :root(0) { }
//destructor
BSTree::~BSTree()
{
root = makeEmpty(root);
}
void BSTree::displayPreorder()
{
preorder(root);
cout << endl;
}
void BSTree::displayInorder()
{
inorder(root);
cout << endl;
}
void BSTree::displayPostorder()
{
postorder(root);
cout << endl;
}
treeNode* BSTree::makeEmpty(treeNode* t)
{
if (t == NULL)
return NULL;
{
makeEmpty(t->leftChild);
makeEmpty(t->rightChild);
delete t;
}
return NULL;
}
treeNode* BSTree::findMin(treeNode* t)
{
if (t == NULL)
return NULL;
else if (t->leftChild == NULL)
return t;
else
return findMin(t->leftChild);
}
treeNode* BSTree::findMax(treeNode* t)
{
if (t == NULL)
return NULL;
else if (t->rightChild == NULL)
return t;
else
return findMax(t->rightChild);
}
return t;
}
void BSTree::preorder(treeNode* t)
{
if (t == NULL)
return;
cout << "Preorder\n" << "<" << t->data.id << ", " << t->data.age << ", " <<
t->data.name << ">" << endl;
preorder(t->leftChild);
preorder(t->rightChild);
}
void BSTree::inorder(treeNode* t)
{
if (t == NULL)
return;
inorder(t->leftChild);
cout << "Inorder\n" << "<" << t->data.id << ", " << t->data.age << ", " << t-
>data.name << ">" << endl;
inorder(t->rightChild);
}
void BSTree::postorder(treeNode* t)
{
if (t == NULL)
return;
postorder(t->leftChild);
postorder(t->rightChild);
cout << "Postorder\n" << "<" << t->data.id << ", " << t->data.age << ", " <<
t->data.name << ">" << endl;
}
int main() {
BSTree tree1;
Student std[7] = { { 103, 19, "Wang" }, { 102, 22, "Lin" }, { 101, 20, "Tsai"
}, { 104, 26, "Lee" }, { 106, 24, "Jack" }, { 105, 19, "Pass" }, {103, 25, "Huang"}
};
// A 103 拆解為二元樹後
順序 A
// / \ 102 104
/ \
// B C 101 106
B D
// / \ / \ 105
/ \
// D E F G
C E
for (int i = 0; i < 7; ++i) { //
/
tree1.addNode(std[i]); //
F
}
cout << "Preorder" << endl;// A->B->D->E->C->F->G
tree1.displayPreorder();
cout << "Inorder" << endl;// D->B->E->A->F->C->G
tree1.displayInorder();
cout << "Postorder" << endl;// C->B->F->E->D->A
tree1.displayPostorder();
tree1.deleteNode(103);