判断是否是一个二叉搜索树
定义一个二叉树
#include <stack>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <iostream>
using namespace std;
class Node{
public:
int value;
Node* left;
Node* right;
Node(int value):value(value){
left = nullptr;
right = nullptr;
}
};
生成一个搜索二叉树
//生成一个二叉搜索树
Node *binarySearchTreeInit(){
Node *head = new Node(4);
head->left = new Node(2);
head->right = new Node(6);
head->left->left = new Node(1);
head->left->right = new Node(3);
head->right->left = new Node(5);
head->right->right = new Node(7);
return head;
}
三种算法判断
//判断一个二叉树是否是搜索二叉树
//前中后序遍历(任选一个)递归
static int preValue = INT_MIN;
bool isBSTbyRecur(Node *head){
if(head == nullptr){
return true;
}
bool isABST = isBSTbyRecur(head->left);
if(!isABST){
return false;
}
if(preValue >= head->value){
return false;
}else{
preValue = head->value;
}
return isBSTbyRecur(head->right);
}
//中序遍历判断是否是搜索树
bool isBSTByNoRecur(Node *head){
if(head == nullptr){
return true;
}
stack<Node*> s;
int preValueInNoRecur = INT_MIN;
while(!s.empty() || head != nullptr){
if(head != nullptr){
s.push(head);
head = head->left;
}else{
head = s.top();
s.pop();
if(preValueInNoRecur >= head->value){
return false;
}else{
preValueInNoRecur = head->value;
}
head = head->right;
}
}
return true;
}
//递归判断(二叉树动态规划方法)
class ReturnData{
public:
bool isSearch;
int minValue;
int maxValue;
ReturnData(bool is, int min, int max):
isSearch(is), minValue(min), maxValue(max)
{}
};
ReturnData* isBSTByDP(Node *head){
if(head == nullptr){
return nullptr;
}
int minValue = head->value;
int maxValue = head->value;
ReturnData *rd1 = isBSTByDP(head->left);
ReturnData *rd2 = isBSTByDP(head->right);
if(head->left != nullptr){
minValue = min(minValue, rd1->minValue);
maxValue = max(maxValue, rd1->maxValue);
}
if(head->right != nullptr){
minValue = min(minValue, rd2->minValue);
maxValue = max(maxValue, rd2->maxValue);
}
#if 1
bool isSearch = true;
if(head->left!= nullptr
&&
(!rd1->isSearch || rd1->maxValue >= head->value)){
isSearch = false;
}
if(head->right!= nullptr
&&
(!rd2->isSearch || rd2->minValue <= head->value)){
isSearch = false;
}
#else
bool isSearch = false;
if(head->left!= nullptr?(rd1->isSearch && rd1->maxValue<head->value):true
&&
head->right!= nullptr?(rd2->isSearch && rd2->minValue>head->value):true){
isSearch = true;
}
#endif
return new ReturnData(isSearch, minValue, maxValue);
}
主要是给自己看的,所以肯定会出现很多错误哈哈哈哈哈
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律