Skip to content

Commit 414ac35

Browse files
authored
Update validate_binary_search_tree.cpp
revert change
1 parent f30c48e commit 414ac35

File tree

1 file changed

+21
-14
lines changed

1 file changed

+21
-14
lines changed

cpp/neetcode_150/07_trees/validate_binary_search_tree.cpp

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
/*
22
Given root of binary tree, determine if it's valid (left all < curr, right all > curr)
3-
43
Inorder traversal & check if prev >= curr, recursive/iterative solutions
5-
64
Time: O(n)
75
Space: O(n)
86
*/
@@ -21,20 +19,29 @@
2119
class Solution {
2220
public:
2321
bool isValidBST(TreeNode* root) {
24-
using def = function<bool(TreeNode*,long,long)>;
22+
TreeNode* prev = NULL;
23+
return inorder(root, prev);
24+
}
25+
private:
26+
bool inorder(TreeNode* root, TreeNode*& prev) {
27+
if (root == NULL) {
28+
return true;
29+
}
30+
31+
if (!inorder(root->left, prev)) {
32+
return false;
33+
}
34+
35+
if (prev != NULL && prev->val >= root->val) {
36+
return false;
37+
}
38+
prev = root;
2539

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-
};
40+
if (!inorder(root->right, prev)) {
41+
return false;
42+
}
3643

37-
return valid(root, long(INT_MIN)-1, long(INT_MAX)+1);
44+
return true;
3845
}
3946
};
4047

0 commit comments

Comments
 (0)