From 4689e4e80b479be25f7557d05818f5caa723aafa Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Wed, 5 Feb 2025 18:36:31 -0800 Subject: Initial commit. --- .../easy/trees/02_valid_binary_search_tree.cc | 54 ++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 top-interview-questions/easy/trees/02_valid_binary_search_tree.cc (limited to 'top-interview-questions/easy/trees/02_valid_binary_search_tree.cc') diff --git a/top-interview-questions/easy/trees/02_valid_binary_search_tree.cc b/top-interview-questions/easy/trees/02_valid_binary_search_tree.cc new file mode 100644 index 0000000..a071daf --- /dev/null +++ b/top-interview-questions/easy/trees/02_valid_binary_search_tree.cc @@ -0,0 +1,54 @@ +/** + * Definition for a binary tree node. + * 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 isValidBSTRec(TreeNode* root, int* min, int* max) { + if (root->left && root->right) { + int leftMin, leftMax, rightMin, rightMax; + if (!isValidBSTRec(root->left, &leftMin, &leftMax) || + !isValidBSTRec(root->right, &rightMin, &rightMax)) { + return false; + } + *min = std::min(std::min(leftMin, rightMin), root->val); + *max = std::max(std::max(leftMax, rightMax), root->val); + return (leftMax < root->val) && (root->val < rightMin); + } + else if (root->left) { + int leftMin, leftMax; + if (!isValidBSTRec(root->left, &leftMin, &leftMax)) { + return false; + } + *min = std::min(leftMin, root->val); + *max = std::max(leftMax, root->val); + return (leftMax < root->val); + } + else if (root->right) { + int rightMin, rightMax; + if (!isValidBSTRec(root->right, &rightMin, &rightMax)) { + return false; + } + *min = std::min(rightMin, root->val); + *max = std::max(rightMax, root->val); + return (root->val < rightMin); + } + else { + *min = *max = root->val; + return true; + } + } + + bool isValidBST(TreeNode* root) { + if (!root) return true; + int minVal, maxVal; + return isValidBSTRec(root, &minVal, &maxVal); + } +}; -- cgit v1.2.3