判断是不是二叉搜索树【c++】

#include <iostream>
#include <vector>
using namespace std;

//双链表节点结构
typedef struct treeNode {
	int value;
	struct treeNode* left;
	struct treeNode* right;
	treeNode(int x) : value(x), left(nullptr), right(nullptr) {}
} TreeNode;

void inOrderTraversal(TreeNode* root) {
	if (root == nullptr) {
		return;
	}
	inOrderTraversal(root->left);
	std::cout << root->value << " ";
	inOrderTraversal(root->right);
}

bool isValidBST(TreeNode* root, long long min_val, long long max_val)
{
	if (root == nullptr)
	{
		return true;
	}
	if (root->value <= min_val || root->value >= max_val)
	{
		return false;
	}
	bool leftBST = isValidBST(root->left, min_val, root->value);
	bool rightBST = isValidBST(root->right, root->value, max_val);
	return leftBST & rightBST;
}

int main()
{
	// 示例二叉搜索树
	TreeNode *root = new TreeNode(2);
	root->left = new TreeNode(1);
	root->right = new TreeNode(3);

	//示例非二叉搜索树
	//TreeNode *root = new TreeNode(10);
	//root->left = new TreeNode(20);
	//root->right = new TreeNode(5);
	//root->left->left = new TreeNode(4);
	//root->left->right = new TreeNode(3);

	std::cout << "Is valid BST: " << isValidBST(root, LONG_MIN, LONG_MAX) << std::endl;
	system("pause");
	return 0;
}

https://blog.csdn.net/m0_58086930/article/details/120340917

相关推荐

  1. 判断搜索c++】

    2024-04-23 01:54:02       35 阅读
  2. 搜索吗?

    2024-04-23 01:54:02       42 阅读
  3. 判断是否平衡--c++【做题记录】

    2024-04-23 01:54:02       31 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-23 01:54:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-23 01:54:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-23 01:54:02       82 阅读
  4. Python语言-面向对象

    2024-04-23 01:54:02       91 阅读

热门阅读

  1. draw.io使用心得

    2024-04-23 01:54:02       34 阅读
  2. Ps基础学习笔记

    2024-04-23 01:54:02       30 阅读
  3. numpy where函数在二维数组中的使用及应用

    2024-04-23 01:54:02       37 阅读
  4. centos 下如何锁定docker版本

    2024-04-23 01:54:02       32 阅读
  5. xml开发mybatis

    2024-04-23 01:54:02       39 阅读
  6. es 深入了解和索引生命周期管理

    2024-04-23 01:54:02       29 阅读
  7. 【UnityShader预备知识】内置变量和函数

    2024-04-23 01:54:02       27 阅读