二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树:若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;它的左、右子树也分别为二叉排序树。
原理:二叉排序树的查找过程和次优二叉树类似,通常采取二叉链表作为二叉排序树的存储结构。中序遍历二叉排序树可得到一个关键字的有序序列,一个无序序列可以通过构造一棵二叉排序树变成一个有序序列,构造树的过程即为对无序序列进行排序的过程。每次插入的新的结点都是二叉排序树上新的叶子结点,在进行插入操作时,不必移动其它结点,只需改动某个结点的指针,由空变为非空即可。搜索,插入,删除的复杂度等于树高,O(log(n)).
理解:我用一句话概括:左 < 中 < 右。 根据这个原理,我们可以推断:BST的中序遍历必定是严格递增的。也就是有序数列。
BST的相关函数:
#include <iostream>
using namespace std;
// BST的结点
typedef struct node
{
int key;
struct node *lChild, *rChild;
}Node, *BST;
// 在给定的BST中插入结点,其数据域为element, 使之称为新的BST
bool BSTInsert(Node * &p, int element)
{
if(NULL == p) // 空树
{
p = new Node;
p->key = element;
p->lChild = p->rChild = NULL;
return true;
}
if(element == p->key) // BST中不能有相等的值
return false;
if(element < p->key) // 递归
return BSTInsert(p->lChild, element);
return BSTInsert(p->rChild, element); // 递归
}
// 建立BST
void createBST(Node * &T, int a[], int n)
{
T = NULL;
int i;
for(i = 0; i < n; i++)
{
BSTInsert(T, a[i]);
}
}
// 先序遍历
void preOrderTraverse(BST T)
{
if(T)
{
cout << T->key << " ";
preOrderTraverse(T->lChild);
preOrderTraverse(T->rChild);
}
}
// 中序遍历
void inOrderTraverse(BST T)
{
if(T)
{
inOrderTraverse(T->lChild);
cout << T->key << " ";
inOrderTraverse(T->rChild);
}
}
int main()
{
int a[10] = {4, 5, 2, 1, 0, 9, 3, 7, 6, 8};
int n = 10;
BST T;
// 并非所有的a[]都能构造出BST,所以,最好对createBST的返回值进行判断
createBST(T, a, n);
preOrderTraverse(T);
cout << endl;
inOrderTraverse(T);
cout << endl;
return 0;
}
如何判定一个数是不是BST:
一、使用先根遍历,判断大小关系是否正确:t->lchild->valuevaluerchild->value
转自:http://blog.pfan.cn/boxer/4814.html
bool Judge(PBinTree pbt)
{
PBinTreeNode pLeft, pRight;
bool bLeft = false, bRight=false, bRootl=false, bRootr=false;
if(pbt == NULL)
return true;
// 判断根节点
pLeft = pbt->left;
pRight = pbt->right;
if((pLeft && pLeft->data <= pbt->data)||pLeft==NULL)
{
bRootl = true;
}
if((pRight && pRight->data >= pbt->data)||pRight==NULL)
{
bRootr = true;
}
// 判断左右子树
bLeft = Judge(pLeft);
bRight = Judge(pRight);
// 同时满足条件才叫二叉排序树
return( bLeft && bRight && bRootl && bRootr);
}
这种方法主要是根据二叉排序树的定义来实现的。
二、如果二叉树为二叉排序树,那么中序遍历该树应该输出有序结果,每次输出的值应该比其前驱的值要大,否则不是二叉排序树
转自:http://topic.csdn.net/t/20040113/21/2661487.html 【8楼】
int last=0,flag=1;
int Is_BSTree(Bitree T)//判断二叉树T是否二叉排序树,是则返回1,否则返回0
{
if(T->lchild&&flag) Is_BSTree(T->lchild);
if(T->data<last) flag=0; //与其中序前驱相比较
last=T->data;
if(T->rchild&&flag) Is_BSTree(T->rchild);
return flag;
}
这种方法主要利用的是二叉排序树的性质特点。