Skip to content

Commit f30c48e

Browse files
authored
Update validate_binary_search_tree.cpp
Modify solution to be more similar to Neetcode's solution.
1 parent bd81d37 commit f30c48e

File tree

1 file changed

+12
-21
lines changed

1 file changed

+12
-21
lines changed

cpp/neetcode_150/07_trees/validate_binary_search_tree.cpp

Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -21,29 +21,20 @@
2121
class Solution {
2222
public:
2323
bool isValidBST(TreeNode* root) {
24-
TreeNode* prev = NULL;
25-
return inorder(root, prev);
26-
}
27-
private:
28-
bool inorder(TreeNode* root, TreeNode*& prev) {
29-
if (root == NULL) {
30-
return true;
31-
}
32-
33-
if (!inorder(root->left, prev)) {
34-
return false;
35-
}
36-
37-
if (prev != NULL && prev->val >= root->val) {
38-
return false;
39-
}
40-
prev = root;
24+
using def = function<bool(TreeNode*,long,long)>;
4125

42-
if (!inorder(root->right, prev)) {
43-
return false;
44-
}
26+
def valid = [&] (auto node, long left, long right) {
27+
if(!node){
28+
return true;
29+
}
30+
if(!(node->val < right && node->val > left)){
31+
return false;
32+
}
33+
return (valid(node->left, left, node->val) &&
34+
valid(node->right, node->val, right));
35+
};
4536

46-
return true;
37+
return valid(root, long(INT_MIN)-1, long(INT_MAX)+1);
4738
}
4839
};
4940

0 commit comments

Comments
 (0)