s0098
This commit is contained in:
parent
c442846324
commit
5b947bfadc
11
include/s0098_validate_binary_search_tree.hpp
Normal file
11
include/s0098_validate_binary_search_tree.hpp
Normal 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
|
35
src/s0098_validate_binary_search_tree.cpp
Normal file
35
src/s0098_validate_binary_search_tree.cpp
Normal 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;
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user