二叉树的常规例程,包括插入节点、删除节点、清空二叉树、是否包含某一节点等
方便起见,二叉树节点类的三个变量没有进行封装,实际操作中应设置为
template<typename T>
class BinaryTree{
private:
T element;
BinaryTree* left;
BinaryTree* right;
public:
BinaryTree(T e, BinaryTree* l = NULL, BinaryTree* r = NULL) :element(e), left(l), right(r){}
T getElement(){return this->element;}
BinaryTree* getLeft(){return this->left;}
BinaryTree* getRight(){return this->right;}
void setElement(const T & x){this->element = x;}
void setLeft(const BinaryTree* & l){this->left = l;}
void setRight(const BinaryTree* & r){this->right = r;}
};
详细代码
#include<iostream>
#include<cstdlib>
using namespace std;
template<typename T>
class BinaryTree{
public:
T element;
BinaryTree* left;
BinaryTree* right;
BinaryTree(T e, BinaryTree* l = NULL, BinaryTree* r = NULL) :element(e), left(l), right(r){}
};
template<typename T>
class binarySearchTree{
private:
BinaryTree<T> * root;
public:
//构造函数
binarySearchTree(){
root = NULL;
}
//插入节点
void insert(const T & x){
insert(x, root);
}
//删除节点
void remove(const T & x){
remove(x, root);
}
//输出树
void printTree(){
cout << "中序" << endl;
printTree(root);
cout << endl << "后序" << endl;
printTree(root, 1);
}
//是否包含某一节点
bool contains(const T & x)const{
return contains(x, root);
}
//清空二叉树
void makeEmpty(){
makeEmpty(root);
}
private:
void insert(const T & x, BinaryTree<T>*&t){
if (t == NULL){
t = new BinaryTree<T>(x);
}
else if (x < t->element){
insert(x, t->left);
}
else if (t->element < x){
insert(x, t->right);
}
else{
;
}
}
BinaryTree<T>* findMax( BinaryTree<T>* t)const{
if (t == NULL){
return NULL;
}
if (t->right == NULL){
return t;
}
return findMax(t->right);
}
BinaryTree<T>* findMin(BinaryTree<T>* t)const{
if (t == NULL){
return NULL;
}
else if (t->left == NULL){
return t;
}
else{
return findMin(t->left);
}
}
void remove(const T & x, BinaryTree<T>* &t){
if (t == NULL){
return;
}
else if (x < t->element){
remove(x, t->left);
}
else if (x > t->element){
remove(x, t->right);
}
// t->element == x
//有两个孩子
//把数值替换成右孩子中最小的值
//递归地删除右孩子中该最小的点
else if (t->left != NULL && t->right != NULL)
{
t->element = findMin(t->right)->element;
remove(t->element, t->right);
}
//只有一个孩子
//就让指向该节点的指针t指向孩子节点
//然后删除该节点
//该节点的父节点还是会指向t节点
//完成删除
else{
BinaryTree<T>* oldNode = t;
t = (t->left) ? t->left : t->right;
delete oldNode;
}
}
void printTree(BinaryTree<T>*t)const{
if (t != NULL){
printTree(t->left);
cout << t->element << ' ';
printTree(t->right);
}
}
void printTree(BinaryTree<T>*t, int x)const{
if (t != NULL){
printTree(t->left,1);
printTree(t->right,1);
cout << t->element << ' ';
}
}
bool contains(const T& x, BinaryTree<T>*t)const{
if (t == NULL){
return false;
}
else if (t->element < x){
return contains(x, t->right);
}
else if (t->element > x){
return contains(x, t->left);
}
else{
return true;
}
}
void makeEmpty(BinaryTree<T>*&t){
if (t != NULL){
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
}
t = NULL;
}
};