File tree Expand file tree Collapse file tree 1 file changed +21
-14
lines changed
cpp/neetcode_150/07_trees Expand file tree Collapse file tree 1 file changed +21
-14
lines changed Original file line number Diff line number Diff line change 1
1
/*
2
2
Given root of binary tree, determine if it's valid (left all < curr, right all > curr)
3
-
4
3
Inorder traversal & check if prev >= curr, recursive/iterative solutions
5
-
6
4
Time: O(n)
7
5
Space: O(n)
8
6
*/
21
19
class Solution {
22
20
public:
23
21
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;
25
39
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
+ }
36
43
37
- return valid (root, long (INT_MIN)- 1 , long (INT_MAX)+ 1 ) ;
44
+ return true ;
38
45
}
39
46
};
40
47
You can’t perform that action at this time.
0 commit comments