// 给你树的实现方法,以前写的,你可以先思考一下
// main.cpp
// BTree(二叉树的实现)
//
#include
#include
using namespace std;
//二叉树的每个节点
class TreeNode {
public:
//无参构造方法
TreeNode() {
left = right = 0;
}
//有参构造方法
TreeNode(int info, TreeNode * l = 0, TreeNode * r = 0) {
this->info = info;
this->left = l;
this->right = r;
successor = 0;
}
//节点中储存的信息
int info;
//左节点
TreeNode * left;
//右节点
TreeNode * right;
//表示节点有没有后继
unsigned int successor : 1;
};
class BTree {
public:
//构造函数
BTree() {
root = 0;
}
//析构函数
~BTree() {
}
//遍历树
void visitAllInfo() {
stack st;
TreeNode * p = root;
if (p != 0) {
st.push(p);
while (!st.empty()) {
p = st.top();
st.pop();
cout<info<<" ";
if (p->right != 0) {
st.push(p->right);
}
if (p->left != 0) {
st.push(p->left);
}
}
cout< } else {
cout<<"树为空!"< }
}
//插入元素
void insertInfo(int e) {
TreeNode * p, * prev = 0, * newNode;
newNode = new TreeNode(e);
//如果树是空的,直接插入就好
if (root == 0) {
root = newNode;
return;
}
p = root;
while (p != 0) {
prev = p;
if (p->info > e) {
p = p->left;
} else if(p->successor == 0) {
p = p->right;
} else {
break;
}
}
if (prev->info > e) {
prev->left = newNode;
newNode->successor = 1;
//newNode->right = prev;
} else if(prev->successor == 1) {
newNode->successor = 1;
prev->successor = 0;
newNode->right = prev->right;
prev->right = newNode;
} else prev->right = newNode;
}
//删除一个节点(方便删除元素时使用)
void deleteANode(TreeNode * & p) {
TreeNode *temp = p;
if (p != 0) {
if (p->right == 0) {
p = p->left;
} else if(p->left == 0) {
p = p->right;
} else {
temp = p->left;
while (temp->right != 0) {
temp = temp->right;
}
temp->right = p->right;
temp = p;
p = p->left;
}
delete temp;
}
}
//删除元素
void deleteInfo(int e) {
TreeNode * p = root, * prev = 0;
//找到要删除的位置
while (p != 0) {
if (p->info == e) {
break;
}
prev = p;
if (p->info < e) {
p = p->right;
}else{
p = p->left;
}
}
//如果找到了
if (p != 0 && p->info == e) {
if (p == root) {
deleteANode(root);
//cout<<"删除根节点成功"< } else if(prev->left == p) {
deleteANode(prev->left);
} else {
deleteANode(prev->right);
}
} else if(root != 0) {
//如果没找到分两种情况 1.没有这个元素
cout<<"找不到元素"< } else {
//2.树是空的
cout<<"树是空的!"< }
}
bool isEmpty() {
return root == 0;
}
private:
//根节点
TreeNode * root;
};
int main()
{
//测试
BTree *tree = new BTree();
//插入一些元素
tree->insertInfo(1);
tree->insertInfo(2);
tree->insertInfo(4);
tree->insertInfo(3);
tree->insertInfo(5);
tree->insertInfo(7);
tree->insertInfo(6);
//输出全部信息
tree->visitAllInfo();
//删除元素
tree->deleteInfo(9);
//
//tree->visitAllInfo();
tree->deleteInfo(2);
tree->visitAllInfo();
return 0;
}