diff --git a/include/s0098_validate_binary_search_tree.hpp b/include/s0098_validate_binary_search_tree.hpp new file mode 100644 index 0000000..aa5356f --- /dev/null +++ b/include/s0098_validate_binary_search_tree.hpp @@ -0,0 +1,11 @@ +#ifndef S0098_VALIDATE_BINARY_SEARCH_TREE_HPP +#define S0098_VALIDATE_BINARY_SEARCH_TREE_HPP + +#include "structures.hpp" + +class S0098 { + public: + bool isValidBST(TreeNode* root); +}; + +#endif diff --git a/src/s0098_validate_binary_search_tree.cpp b/src/s0098_validate_binary_search_tree.cpp new file mode 100644 index 0000000..6efaf43 --- /dev/null +++ b/src/s0098_validate_binary_search_tree.cpp @@ -0,0 +1,35 @@ +#include "s0098_validate_binary_search_tree.hpp" + +struct TreeNodeState_S0098 { + int maxVal; + int minVal; + bool isValidBST; +}; + +TreeNodeState_S0098 isValidBSTHelper(TreeNode* root) { + if (root == nullptr) return TreeNodeState_S0098{0, 0, false}; + if (root->left == nullptr && root->right != nullptr) { + TreeNodeState_S0098 rightState = isValidBSTHelper(root->right); + return TreeNodeState_S0098{ + rightState.maxVal, root->val, + root->val < rightState.minVal && rightState.isValidBST}; + } else if (root->left != nullptr && root->right == nullptr) { + TreeNodeState_S0098 leftState = isValidBSTHelper(root->left); + return TreeNodeState_S0098{ + root->val, leftState.minVal, + root->val > leftState.maxVal && leftState.isValidBST}; + } else if (root->left != nullptr && root->right != nullptr) { + TreeNodeState_S0098 leftState = isValidBSTHelper(root->left); + TreeNodeState_S0098 rightState = isValidBSTHelper(root->right); + return TreeNodeState_S0098{ + rightState.maxVal, leftState.minVal, + root->val > leftState.maxVal && root->val < rightState.minVal && + leftState.isValidBST && rightState.isValidBST}; + } else { + return TreeNodeState_S0098{root->val, root->val, true}; + } +} + +bool S0098::isValidBST(TreeNode* root) { + return isValidBSTHelper(root).isValidBST; +}