#include <iostream>
using namespace std;
class TreeNode {
public:
int data;
TreeNode *LeftChild;
TreeNode *RightChild;
TreeNode() :LeftChild(NULL), RightChild(NULL) {}
};
class BiSortTree {
private:
TreeNode *root;
int *info;
int size;
int loc;
int count;
TreeNode *CreateTree(TreeNode *p);
TreeNode* InsertNode(TreeNode *p, int d);
int Search(TreeNode *p, int d);
void Delete(int d);
public:
BiSortTree(int s, int arr[]);
void CreateBiSortTree();
void InsertBiSortTree(int d);
void InOder(TreeNode *p);
void InOderTree();
void SearchData(int d);
void DeleteData(int d);
};
BiSortTree::BiSortTree(int s, int arr[]) {
loc = 1;
count = 0;
size = s;
info = new int[size];
for (int i = 0; i < size; i++)
info[i] = arr[i];
}
void BiSortTree::CreateBiSortTree() {
root = new TreeNode();
if (size)
root->data = info[0];
CreateTree(root);
}
TreeNode *BiSortTree::CreateTree(TreeNode *p) {
if (loc < size) {
if (p->data > info[loc]) {
if (!p->LeftChild) {
p->LeftChild = new TreeNode();
p->LeftChild->data = info[loc++];
}
else
CreateTree(p->LeftChild);
}
else
if (p->data < info[loc]) {
if (!p->RightChild) {
p->RightChild = new TreeNode();
p->RightChild->data = info[loc++];
}
else
CreateTree(p->RightChild);
}
CreateTree(root);
}
return NULL;
}
void BiSortTree::InOderTree() {
InOder(root);
}
void BiSortTree::InOder(TreeNode *p) {
if (p) {
InOder(p->LeftChild);
cout << p->data << ' ';
InOder(p->RightChild);
}
}
void BiSortTree::Delete(int d) {
TreeNode *p = root;
TreeNode *f = new TreeNode();
while (p && p->data != d ) {
f = p;
if (p->data > d)
p = p->LeftChild;
else
p = p->RightChild;
}
TreeNode * q;
if (!p)
return;
if (p->LeftChild && p->RightChild) {
if (!p->LeftChild->RightChild) {
p ->data = p->LeftChild->data;
p->LeftChild = p->LeftChild->LeftChild;
}
else {
TreeNode *q = p->LeftChild;
TreeNode *t = q;
while (t->RightChild) {
q = t;
t = t->RightChild;
}
p->data = t->data;
q->RightChild = t->LeftChild;
}
}
else {
if (!p->LeftChild) {
f->RightChild = p->RightChild;
delete p;
}
else {
f->LeftChild = p->LeftChild;
delete p;
}
}
}
void BiSortTree::DeleteData(int d) {
Delete(d);
}
int main() {
int t;
cin >> t;
while (t--) {
int s;
cin >> s;
int *arr = new int[s];
for (int i = 0; i < s; i++)
cin >> arr[i];
BiSortTree sTree(s, arr);
sTree.CreateBiSortTree();
sTree.InOderTree();
cout << endl;
int m;
cin >> m;
while (m--) {
int d;
cin >> d;
sTree.DeleteData(d);
sTree.InOderTree();
cout<<endl;
}
}
//system("pause");
return 0;
}
/*InPut
1
6
22 33 55 66 11 44
3
66
22
77
*/
/*OutPut
11 22 33 44 55 66
11 22 33 44 55
11 33 44 55
11 33 44 55
*/
C++二叉排序樹之刪除結點
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.