This commit is contained in:
Sainnhe Park 2023-01-31 15:30:31 +08:00
parent c442846324
commit 5b947bfadc
2 changed files with 46 additions and 0 deletions

View File

@ -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

View File

@ -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;
}