isValidBST created by Hexe - https://repl.it/@Hexe/isValidBST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <climits> | |
struct TreeNode { | |
int val; | |
TreeNode* left; | |
TreeNode* right; | |
TreeNode(int x): val(x), left(nullptr), right(nullptr) {} | |
}; | |
class ValidateBST { | |
public: | |
bool isValidBST(TreeNode* root) { | |
return isValidBST(root, INT_MIN, INT_MAX); | |
} | |
private: | |
bool isValidBST(TreeNode* node, int lower, int upper) { | |
if (node == nullptr) return true; | |
int val = node->val; | |
return val >= lower && val <= upper | |
&& isValidBST(node->left, lower, val) | |
&& isValidBST(node->right, val, upper); | |
} | |
}; | |
using namespace std; | |
int main() { | |
auto root = new TreeNode(5); | |
root->left = new TreeNode(3); | |
root->right = new TreeNode(9); | |
root->right->right = new TreeNode(10); | |
ValidateBST solution = ValidateBST(); | |
cout << solution.isValidBST(root); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment