C++ 判断二叉排序树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HarvestWu/article/details/81209659
#include <bits/stdc++.h>
#define MaxSize 100
#define MIN -10000
#define TRUE 1
#define FALSE 0
#define ArrayLen(array) sizeof(array)/sizeof(array[0])
/*
* Created by HarvestWu on 2018/07/25.
*/
using namespace std;

//定义二叉树结构
typedef struct BTNode
{
	int key;
	struct BTNode *lchild;
	struct BTNode *rchild;
} BTNode;

//二叉排序树关键字插入
int BSTInsert(BTNode *&bt, int key)
{
	if (bt==NULL)
	{
		bt = (BTNode*)malloc(sizeof(BTNode));
		bt->lchild = bt->rchild = NULL;
		bt->key = key;
		return TRUE;
	}
	else
	{
		if (key == bt->key)
			return FALSE;
		else if (key < bt->key)
			return BSTInsert(bt->lchild, key);
		else return BSTInsert(bt->rchild, key);
	}
}

//创建二叉排序树
void CreateBST(BTNode *&bt, int key[], int n)
{
	bt = NULL;
	for (int i = 0; i < n; ++i)
		BSTInsert(bt, key[i]);
}

//判断二叉排序树
int pre = MIN;
int JudgeBST(BTNode *bt)
{
	int flag1, flag2;
	if (bt == NULL)
		return TRUE;
	else
	{
		flag1 = JudgeBST(bt->lchild);
		if (flag1 == FALSE || pre > bt->key)
			return FALSE;
		pre = bt->key;
		flag2 = JudgeBST(bt->rchild);
		return flag2;
	}
}

int main()
{
	BTNode *bt;
	int key[] = { 1, 5, 7, 6, 3, 4, 8, 9, 2 };
	int n = ArrayLen(key);
	CreateBST(bt, key, n);//创建BST
	cout << endl << JudgeBST(bt) << endl;//判断BST
	return 0;
}

猜你喜欢

转载自blog.csdn.net/HarvestWu/article/details/81209659