二叉排序树
基本思路:
1、使用随机数构建二叉排序树,若树空则新建节点,若大于节点就递归插入右子树,若小于节点则递归构建左子树。
2、中序遍历即可升序输出,调整左子树与右子树遍历顺序即可降序输出。
3、查找:若与节点匹配成功,则返回节点指针,若小于节点则递归查找左子树,若大于则递归查找右子树。
代码实现:
#include <iostream>
using namespace std;
typedef struct BSTNode
{
int data;
struct BSTNode*lchild, *rchild;
}BSTNode, *BSTree;
void InsertBST(BSTree &T, int e)//插入二叉排序树
{
if (!T)
{
BSTree S;
S = new BSTNode;
S->data = e;
S->lchild = S->rchild = NULL;
T = S;
}
else if (e<T->data)
InsertBST(T->lchild, e);
else if (e>T->data)
InsertBST(T->rchild, e);
}
void INitBST(BSTree &T)//初始化二叉排序树
{
int i = 0;
for (int j = 0; j<10; j++)
{
i = rand() % 100;
InsertBST(T, i);
}
}
void AscendOutput(BSTree &T)//升序//相当于中序遍历
{
if (T)
{
AscendOutput(T->lchild);
cout << T->data << "\t";
AscendOutput(T->rchild);
}
}
void DesendOutput(BSTree &T)//降序
{
if (T)
{
DesendOutput(T->rchild);
cout << T->data << "\t";
DesendOutput(T->lchild);
}
}
BSTree SearchBST(BSTree T, int key)//查找
{
if ((!T) || key == T->data)
return T;
else if (key<T->data)
return SearchBST(T->lchild, key);
else return SearchBST(T->rchild, key);
}
int main()
{
BSTNode *T;
T = NULL;
INitBST(T);
cout << "升序序列:";
AscendOutput(T);
cout << endl << "降序序列:";
DesendOutput(T);
BSTree t = SearchBST(T, 99);
if (t)
cout << endl << "查找成功";
else
cout << endl << "查找失败";
}