二叉排序树的构造、查找、插入及删除算法的实现(C++)
转自
这里
#include <iostream>
using namespace std;
class BsTree {
public:
// 构造函数初始化树根为NULL,表示空树
BsTree (void) : m_pRoot (NULL), m_uSize (0) {}
// 析构函数清空树
~BsTree (void) {
Clear ();
}
// 插入数据
void Insert (int nData) {
Insert (new Node (nData), m_pRoot);
m_uSize++;
}
// 删除数据,不存在返回false
bool Remove (int nData) {
Node*& pFind = Find (nData, m_pRoot);
if (pFind) {
Insert (pFind -> m_pLeft, pFind -> m_pRight);
Node* pNode = pFind;
pFind = pFind -> m_pRight;
delete pNode;
m_uSize--;
return true;
}
return false;
}
// 删除所有值为nData的数据
void RemoveAll (int nData) {
while (Remove (nData));
}
// 清空树
void Clear (void) {
Clear (m_pRoot);
m_uSize = 0;
}
// 将全部nOld改为nNew
void Update (int nOld, int nNew) {
while (Remove (nOld))
Insert (nNew);
}
// 树中能否找到nData
bool Find (int nData) {
return Find (nData, m_pRoot) != NULL;
}
// 中序遍历
void Travel (void) {
cout << '{';
Travel (m_pRoot);
cout << '}' << endl;
}
// 获取树的大小
size_t GetSize (void) {
return m_uSize;
}
// 获取树的高度
size_t GetHeight (void) {
return GetHeight (m_pRoot);
}
private:
// 节点类
class Node {
public:
Node (int nData) : m_nData (nData), m_pLeft (NULL), m_pRight (NULL) {}
int m_nData; // 数据
Node* m_pLeft; // 左树
Node* m_pRight; // 右树
};
void Insert (Node* pNode, Node*& pTree) {
if (! pTree)
pTree = pNode;
else if (pNode) {
if (pNode -> m_nData<pTree -> m_nData)
Insert (pNode, pTree -> m_pLeft);
else
Insert (pNode, pTree -> m_pRight);
}
}
Node*& Find (int nData, Node*& pTree) {
if (! pTree)
return pTree;
else
if (nData == pTree -> m_nData)
return pTree;
else
if (nData < pTree -> m_nData)
return Find (nData, pTree -> m_pLeft);
else
return Find (nData, pTree -> m_pRight);
}
void Clear (Node*& pTree) {
if (pTree) {
Clear (pTree -> m_pLeft);
Clear (pTree -> m_pRight);
delete pTree;
pTree = NULL;
}
}
void Travel (Node*& pTree) {
if (pTree) {
Travel (pTree -> m_pLeft);
cout << '<' << pTree -> m_nData << '>';
Travel (pTree -> m_pRight);
}
}
size_t GetHeight (Node*& pTree) {
if (pTree) {
size_t uLeft=GetHeight(pTree->m_pLeft);
size_t uRight=GetHeight(pTree->m_pRight);
return uLeft>uRight?uLeft+1:uRight+1;
}
return 0;
}
Node* m_pRoot; // 树根
size_t m_uSize; // 树大小
};
int main (void) {
//以下为测试代码
BsTree bt;
bt.Insert (4);
bt.Insert (3);
bt.Insert (6);
bt.Insert (9);
bt.Travel ();
cout << boolalpha << bt.Find (3) << endl;
cout << boolalpha << bt.Find (100) << endl;
bt.Remove (4);
bt.Travel ();
bt.Remove (3);
bt.Travel ();
bt.Insert (10);
bt.Insert (20);
bt.Insert (30);
bt.Insert (10);
bt.Travel ();
bt.Update (10, 100);
bt.Travel ();
bt.RemoveAll (100);
bt.Travel ();
cout << bt.GetSize () << endl;
cout << bt.GetHeight () << endl;
bt.Clear ();
bt.Travel ();
bt.Insert (6);
bt.Insert (2);
bt.Insert (3);
bt.Insert (4);
bt.Insert (7);
bt.Travel ();
cout << bt.GetHeight () << endl;
return 0;
}