数据结构—判断一棵树是否是二叉搜索树
代码:
#pragma once
#define N 100
#define elemType BTree*
#include<stdlib.h>
typedef struct BTree {
int data;
struct BTree *lchild, *rchild;
}BTree;
typedef struct dQueue {
elemType data;
struct dQueue* next;
}dQueue;
typedef struct queue {
dQueue *front, *rear;
}queue;
bool initQueue(queue &Queue) {//初始化队列
//Queue.front = new dQueue;
Queue.front = Queue.rear = (dQueue*)malloc(sizeof(dQueue));
if (!Queue.front) {
return false;
}
Queue.front->next = NULL;//头结点
return true;
}
elemType getQueueTopElem(queue &Queue) {//获取队列队头的元素
elemType u=NULL ;
if (Queue.front != Queue.rear) {
dQueue* p = Queue.front->next;
u = p->data;
}
return u;
}
bool enQueue(queue &Queue, elemType e) {//入队
dQueue* p = Queue.rear;
dQueue* s = (dQueue*)malloc(sizeof(dQueue));
s->data = e;
s->next = NULL;
p->next = s;
Queue.rear = s;
return true;
}
bool deQueue(queue &Queue, elemType &e) {//出队
if (Queue.front == Queue.rear) {
return false;//空队
}
dQueue* p = Queue.front->next;
e = p->data;
Queue.front->next = p->next;
if (p == Queue.rear) {//队尾只有一个元素的时候
Queue.rear = Queue.front;
}
delete p;
return true;
}
bool emptyQueue(queue Queue) {//队列为空的判断
if (Queue.front == Queue.rear) {
return true;
}
return false;
}
#include <stdio.h>
#include <stdlib.h>
//#include "BTree.h"
#include"queue.h"
int preElem = -1;
void createBSTTree(BTree* & T, int data) {//创建二叉排序树
BTree *p = NULL;
if (!T) {
p = (BTree*)malloc(sizeof(BTree));
p->data = data;
p->lchild = p->rchild = NULL;
T = p;
return;
}
if (data < T->data) {//左子树插入
createBSTTree(T->lchild, data);
}
else {//右子树插入
createBSTTree(T->rchild, data);
}
}
int isBST(BTree* bTree) {//必须满足严格的左子树结点的值小于跟结点的值,右节点的值大于根节点的值
int b1, b2;//中序遍历+递归返回值影响
if (bTree == NULL) {//小条件退出
return 1;
}
else {
b1 = isBST(bTree->lchild);
if (b1 == 0 || preElem >= bTree->data) {
return 0;
}
preElem = bTree->data;
b2 = isBST(bTree->rchild);
return b2;
}
}
int isBST2(BTree* btree) {//非递归
queue q;
initQueue(q);
enQueue(q, btree);
while (!emptyQueue(q)) {
BTree* temp;
deQueue(q, temp);
if (temp&&temp->lchild) {
if(temp->lchild->data >= temp->data)
return 0;
else
enQueue(q, temp->lchild);
}
if (temp&&temp->rchild) {
if (temp->rchild->data < temp->data)
return 0;
else
enQueue(q, temp->rchild);
}
}
return 1;
}
void midTraverseTree(BTree* BSTTree) {//中序遍历二叉排序树
if (BSTTree) {
midTraverseTree(BSTTree->lchild);
printf("%d ", BSTTree->data);
midTraverseTree(BSTTree->rchild);
}
}
int main() {
BTree* T = NULL;//一定要初始化为空树
int count, data;
printf("开始构造二叉排序树:\n输入二叉排序树结点的数目:");
scanf_s("%d", &count);
while (count--) {//构造二叉排序树
printf("输入二叉树的第%d个结点:", count + 1);
scanf_s("%d", &data);
createBSTTree(T, data);
}
printf("中序遍历二叉树\n");
midTraverseTree(T);//中序遍历二叉排序树
printf("\n方法一判断是否是二叉排序树\n");
if (isBST(T)) {
printf("\n是二叉排序树\n");
}
else {
printf("\n不是二叉排序树\n");
}
printf("\n方法二判断是否是二叉排序树\n");
if (isBST2(T)) {
printf("\n是二叉排序树\n");
}
else {
printf("\n不是二叉排序树\n");
}
printf("\n");
system("pause");
return 0;
}
测试截图:
时间复杂度O(n或nlogn),空间复杂度O(1)
如果存在什么问题,欢迎批评指正!谢谢!