#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;
}
判断某个二叉树是不是二分搜索树
2024-04-23 01:54:02 34 阅读