From 92b6e2833ee2334d860bf7b2b94f9eb116c94178 Mon Sep 17 00:00:00 2001 From: Buduf Date: Thu, 14 Apr 2022 13:36:11 +0200 Subject: [PATCH] problem 98 --- ValidateBinarySearchTree.cpp | 44 ++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 ValidateBinarySearchTree.cpp diff --git a/ValidateBinarySearchTree.cpp b/ValidateBinarySearchTree.cpp new file mode 100644 index 0000000..3b919bf --- /dev/null +++ b/ValidateBinarySearchTree.cpp @@ -0,0 +1,44 @@ +#include + +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} +}; + +class Solution { +public: + bool isValidBST(TreeNode* root) { + if (root != nullptr) { + return valid(root, INT_MIN, INT_MAX, false, false); + } + else { + return true; + } + } + bool valid(TreeNode* t, int min, int max, bool wasMin, bool wasMax) { + if ((wasMin && t->val <= min) || (wasMax && t->val >= max)) { + return false; + } + if (t->left != nullptr) { + bool l = valid(t->left, min, t->val, wasMin, true); + if (t->right != nullptr) { + return l && valid(t->right, t->val, max, true, wasMax); + } + else { + return l; + } + } + else { + if (t->right != nullptr) { + return valid(t->right, t->val, max, true, wasMax); + } + else { + return true; + } + } + } +};