二叉搜索樹又名爲二叉查找樹、有序二叉樹、查找二叉樹,是一種很重要的基礎性數據結構,支持多種動態集合操作,包括插入、刪除、查找等操作。二叉樹的優勢在於查找、插入的時間複雜度較低,爲O(lg n),不過如果數據不好,最壞的時間複雜度爲O(n),比如把有序的數據插入二叉樹。
二叉搜索樹可以當做字典(其中鍵就是樹節點的關鍵字,值爲任何類型的數據,叫做衛星數據),也可以當做優先隊列。
二叉搜索樹是遞歸定義的,定義是對樹中的任一節點x,左子樹的關鍵字y不大於該節點的關鍵字(key[y]<=key[x]),右子樹的節點的關鍵字y不小於該節點的關鍵字(key[y]>=key[x])。
下面是二叉搜索樹的代碼,花了好長時間調試,有點生疏了。這裏的二叉搜索樹是沒有重複值的。
#ifndef __BSTree_H__
#define __BSTree_H__
#include <cassert>
template <typename T>
struct BSTreeNode {
BSTreeNode *left, *right;
T val;
BSTreeNode(T _val, BSTreeNode *_left=NULL, BSTreeNode *_right=NULL):
val(_val), left(_left), right(_right)
{}
};
template<typename T>
class BSTree {
private:
BSTreeNode<T> *root;
size_t size;
typedef void (*visitFun)(T);
//查找值val節點的父親指針
BSTreeNode<T>* findParent(BSTreeNode<T> *x)
{
assert(x != NULL);
if (x == root)
return NULL;
BSTreeNode<T> *y = root, *p;
while (y != NULL && y->val != x->val) {
p = y;
if (y->val < x->val) {
y = y->right;
} else if (y->val > x->val) {
y = y->left;
}
}
return p;
}
void inOrderTraversal(BSTreeNode<T> *root, visitFun visit)
{
if (root) {
inOrderTraversal(root->left, visit); //訪問左子樹
//cout << root->val << " "; //訪問該節點
visit(root->val);
inOrderTraversal(root->right, visit); //訪問右子樹
}
}
public:
BSTree()
{
root = NULL;
size = 0;
}
~BSTree()
{
releaseMemory(root);
}
// 釋放內存
void releaseMemory(BSTreeNode<T> *root)
{
if (root != NULL) {
releaseMemory(root->left);
releaseMemory(root->right);
delete root;
}
}
//查找值爲val的節點,如果成功查找則返回該節點指針,否則返回NULL
BSTreeNode<T>* find(T val)
{
BSTreeNode<T> *x = root;
while (x != NULL) {
if (x->val < val) {
x = x->right;
} else if (x->val > val) {
x = x->left;
} else {
return x;
}
}
return NULL;
}
//插入val,如果成功插入則返回true,否則(已有值爲val的節點)則返回false
bool insert(T val)
{
if (root == NULL) {
root = new BSTreeNode<T>(val);
++size;
return true;
}
BSTreeNode<T> *x = root, *parent;
while (x != NULL) {
parent = x;
if (x->val < val) {
x = x->right;
} else if (x->val > val) {
x = x->left;
} else { // 二叉搜索樹中已有值val的節點
return false;
}
}
//循環結束後,parent爲葉節點,p爲NULL
BSTreeNode<T> *nodePtr = new BSTreeNode<T>(val);
if (parent->val > val)
parent->left = nodePtr;
else
parent->right = nodePtr;
++size; return true;
}
//刪除值爲val的節點,成功刪除則返回true,否則(沒找到節點)則返回false
//Version 1: 寫得不好,太繁瑣,其實不用找到它的父節點的,可以簡化
/*
bool remove(T val)
{
BSTreeNode<T> *x = find(val);
if (x == NULL) {
return false;
}
BSTreeNode<T> *parent = findParent(x);
// 刪除根節點
if (parent == NULL) {
if (x->left==NULL && x->right==NULL) {
delete x;
root = NULL;
} else if (x->left != NULL) {
BSTreeNode<T> *y = x->left, *py = x;
assert(y!=NULL);
while (y->right != NULL) {
py = y;
y = y->right;
}
//y此時是x左子樹的最右孩子
x->val = y->val;
if (py == x) {
py->left = y->left;
} else {
py->right = y->left;
}
delete y;
} else {
BSTreeNode<T> *y = x->right, *py = x;
assert(y!=NULL);
while (y->left != NULL) {
py = y;
y = y->left;
}
//y此時是x右子樹的最左孩子
x->val = y->val;
if (py == x) {
py->right = y->right;
} else {
py->left = y->right;
}
delete y;
}
}
// x爲葉節點,修改父節點parent指向x的指針爲NULL
else if (x->left==NULL && x->right==NULL) {
parent->val < x->val ? parent->right=NULL : parent->left=NULL;
delete x;
}
// x只有一個子女,刪除x
else if (x->left==NULL || x->right==NULL) {
if (x->left == NULL)
parent->val < x->val ? parent->right=x->right : parent->left=x->right;
else
parent->val < x->val ? parent->right=x->left : parent->left=x->left;
delete x;
}
// x有左右孩子,把x的右子樹最左節點y賦給x,然後刪除y
else {
BSTreeNode<T> *y = x->right, *py = x;
assert(y!=NULL);
while (y->left != NULL) {
py = y;
y = y->left;
}
//y此時是x右子樹的最左孩子
x->val = y->val;
if (py == x) {
py->right = y->right;
} else {
py->left = y->right;
}
delete y;
}
--size;
return true;
}*/
// Version 2: 刪除值爲val的節點
bool remove(T val)
{
BSTreeNode<T> *x = find(val);
if (!x) {
return false;
}
//x爲葉節點,直接刪除即可
if (!x->left && !x->right) {
if (x == root) // 需判斷是否根節點
root = NULL;
delete x;
} else if (!x->right) { // 右子樹爲空,重連左子樹
BSTreeNode<T> *y = x->left;
x->val = y->val;
x->left = y->left;
x->right = y->right;
delete y;
} else if (!x->left) { // 左子樹爲空,重連右子樹
BSTreeNode<T> *y = x->right;
x->val = y->val;
x->left = y->left;
x->right = y->right;
delete y;
} else { //左右子樹非空,把左子樹的最右孩子賦給x後刪除
BSTreeNode<T> *y = x->left, *py = x;
while (y->right) {
py = y;
y = y->right;
}
x->val = y->val;
if (py != x) {
py->right = y->left;
} else {
x->left = y->left;
}
delete y;
}
--size;
return true;
}
// 中序遍歷,可以得到有序的數列
void inOrderTraversal(visitFun visit)
{
inOrderTraversal(root, visit);
}
size_t getSize() const
{
return size;
}
};
#endif
/* Author: freeliao
Time: 2014/1/3 14:00 Modified: 1/4 21:00
Program: Implementation of Binary Serach Tree
Email:[email protected]
*/
#include <iostream>
#include <ctime>
#include <set>
#include <vector>
#include "BSTree.h"
using namespace std;
vector<int> vb, vs;
void visit(int a)
{
cout << a <<" ";
}
void copy(int a)
{
vb.push_back(a);
}
int main()
{
BSTree<int> bst;
srand(unsigned(time(NULL)));
const int MAXNUM = 1000, n = 100;
int a[MAXNUM], num;
set<int> s;
for (int i=0; i<n; ++i) {
num = rand() % MAXNUM;
a[i] = num;
bst.insert(a[i]);
s.insert(a[i]);
}
assert(s.size() == bst.getSize());
cout << "元素個數" << bst.getSize() << endl;
cout << "===================================\n";
cout << "比較bst與set元素是否相等\n";
bst.inOrderTraversal(copy);
vs.assign(s.begin(), s.end());
assert(vb == vs);
cout << "相等\n";
cout << "==================================\n";
cout << "從小到大排序結果...\n";
bst.inOrderTraversal(visit);
cout << endl;
cout << "=====================================\n";
for (int i=0; i<10; ++i) {
cout << "刪除" << a[i] << ":";
s.erase(a[i]);
if (bst.remove(a[i]) == true)
cout << "成功\n";
else
cout << "失敗\n";
}
cout << s.size() << " " << bst.getSize() << endl;
assert(s.size() == bst.getSize());
cout << "==================================\n";
cout << "從小到大排序結果...\n";
bst.inOrderTraversal(visit);
cout << endl;
cout << "===================================\n";
cout << "比較bst與set元素是否相等\n";
vb.clear();
bst.inOrderTraversal(copy);
vs.clear();
vs.assign(s.begin(), s.end());
assert(vb == vs);
cout << "相等\n";
system("pause");
return 0;
}
經過多次測試沒有任何問題,雖然代碼寫得不夠精煉。
運行結果如下: