一、基本概念
二叉查找树算是树里面比较常用而且重要的一类,二叉查找树相对于二叉树的不同之处在于,查找树中的每个节点X,它的左子树中的所有关键字要小于X的关键字值,而X的右子树中所有关键字的值大于X的关键字值。这种结构让二叉树按照一定的顺序排序,实现和搜索都会比较简单。
二叉查找树的平均深度为O(log N)。
二、二叉查找树的实现
BSTree.h
#pragma once
#include<iostream>
using namespace std;
typedef int ElementType;
struct BSTreeNode;
typedef BSTreeNode *ptrTree;
typedef ptrTree BSTree;
BSTree createBsTree(ElementType e);
ptrTree findX(ElementType e, BSTree t);
ptrTree findMin(BSTree t);
ptrTree findMax(BSTree t);
BSTree insertX(ElementType e, BSTree t);
BSTree deleteX(ElementType e, BSTree t);
void disposeTree(BSTree t);
struct BSTreeNode
{
ElementType element;
ptrTree left;
ptrTree right;
};
BSTree.cpp
#include "stdafx.h"
#include "BSTree.h"
BSTree createBsTree(ElementType e)
{
BSTree bst = (BSTree)malloc(sizeof(struct BSTreeNode));
if (bst==nullptr)
{
return nullptr;
}
bst->element = e;
bst->left = nullptr;
bst->right = nullptr;
return bst;
}
ptrTree findX(ElementType e, BSTree t)
{
if (t==nullptr)
{
return nullptr;
}
if (e>t->element)
{
return findX(e, t->right);
}
else if(e<t->element)
{
return findX(e, t->left);
}
return t;
}
ptrTree findMin(BSTree t)
{
if (t==nullptr)
{
return nullptr;
}
if (t->left==nullptr)
{
return t;
}
else
{
return findMin(t->left);
}
}
ptrTree findMax(BSTree t)
{
if (t==nullptr)
{
return nullptr;
}
if (t->right==nullptr)
{
return t;
}
else
{
return findMax(t->right);
}
}
BSTree insertX(ElementType e, BSTree t)
{
if (t == nullptr)
{
t = createBsTree(e);
}
else if (e > t->element)
{
t->right = insertX(e, t->right);
}
else if(e < t->element)
{
t->left = insertX(e, t->left);
}
return t;
}
BSTree deleteX(ElementType e, BSTree t)
{
if (t==nullptr)
{
return nullptr;
}
ptrTree tmp;
if (e>t->element)
{
t->right = deleteX(e, t->right);
}
else if(e<t->element)
{
t->left = deleteX(e, t->left);
}
else if (t->left&&t->right)
{
tmp = findMin(t->right);
t->element = tmp->element;
t->right = deleteX(tmp->element, t->right);
//tmp = deleteX(tmp->element, tmp);
}
else
{
tmp = t;
if (t->right==nullptr)
{
t = t->left;
}
else
{
t = t -> right;
}
free(tmp);
}
return t;
}
void disposeTree(BSTree t)
{
if (t==nullptr)
{
return;
}
disposeTree(t->left);
disposeTree(t->right);
free(t);
}
main.cpp(测试)
#include "stdafx.h"
#include "BSTree.h"
#include<vld.h>
int _tmain(int argc, _TCHAR* argv[])
{
BSTree bst = createBsTree(6);
bst = insertX(2, bst);
bst = insertX(8, bst);
bst = insertX(1, bst);
bst = insertX(3, bst);
bst = insertX(4, bst);
ptrTree ptrx = findX(3, bst);
cout << "findX: " << ptrx->element << endl;
ptrTree pmin = findMin(bst);
cout << "findMin: " << pmin->element << endl;
ptrTree pmax = findMax(bst);
cout << "findMax: " << pmax->element << endl;
bst = deleteX(2, bst);
bst = deleteX(3, bst);
disposeTree(bst);
return 0;
}