#include <iostream>
using namespace std;
int g_min = -1;
// 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);
}
}
// 后序遍历
void PostOrderTraverse(BST T)
{
if(T)
{
inOrderTraverse(T->lChild);
inOrderTraverse(T->rChild);
cout << T->key << " ";
}
}
// 判断是否为BST
bool isBST(BST T)
{
if(NULL != T)
{
isBST(T->lChild);
if(T->key <= g_min)
return false;
g_min = T->key;
isBST(T->rChild);
}
return true;
}
void printJudge(Node *T)
{
if(isBST(T))
cout << "yes" << endl;
else
cout << "no" << endl;
}
// BST的查找(递归)
Node *BSTSearch1(BST T, int x)
{
if(NULL == T)
return NULL;
if(x == T->key)
return T;
if(x < T->key)
return BSTSearch1(T->lChild, x);
return BSTSearch1(T->rChild, x);
}
// BST的查找(非递归)
Node *BSTSearch2(BST T, int x)
{
Node *p = T;
while(NULL != p && x != p->key) // 找不到,就一直找
{
if(x > p->key)
p = p->rChild;
else
p = p->lChild;
}
return p;
}
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;
PostOrderTraverse(T);
cout << endl;
printJudge(T);
Node *p = NULL;
int x; // 待查找的x
for(x = -10; x < 20; x++)
{
p = BSTSearch1(T, x);
cout << x << ":";
if(NULL == p)
cout << "no" << endl;
else
cout << "yes" << endl;
}
return 0;
}
二叉排序树(BST):建立,遍历(前中后),判定,查找(递归+非递归)
最新推荐文章于 2022-07-03 18:14:17 发布