Skip to content

Commit

Permalink
Update validate_binary_search_tree.cpp
Browse files Browse the repository at this point in the history
Modify solution to be more similar to Neetcode's solution.
  • Loading branch information
KC10201 authored Jul 8, 2022
1 parent bd81d37 commit f30c48e
Showing 1 changed file with 12 additions and 21 deletions.
33 changes: 12 additions & 21 deletions cpp/neetcode_150/07_trees/validate_binary_search_tree.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,29 +21,20 @@
class Solution {
public:
bool isValidBST(TreeNode* root) {
TreeNode* prev = NULL;
return inorder(root, prev);
}
private:
bool inorder(TreeNode* root, TreeNode*& prev) {
if (root == NULL) {
return true;
}

if (!inorder(root->left, prev)) {
return false;
}

if (prev != NULL && prev->val >= root->val) {
return false;
}
prev = root;
using def = function<bool(TreeNode*,long,long)>;

if (!inorder(root->right, prev)) {
return false;
}
def valid = [&] (auto node, long left, long right) {
if(!node){
return true;
}
if(!(node->val < right && node->val > left)){
return false;
}
return (valid(node->left, left, node->val) &&
valid(node->right, node->val, right));
};

return true;
return valid(root, long(INT_MIN)-1, long(INT_MAX)+1);
}
};

Expand Down

0 comments on commit f30c48e

Please sign in to comment.