Skip to content

Commit 40761bd

Browse files
committed
validate-bin-search-tree
1 parent 076b11c commit 40761bd

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
bool dfs(TreeNode* root, long minVal, long maxVal) {
15+
if(!(minVal < root->val && root->val < maxVal)) return false;
16+
bool isValid = true;
17+
if(root->left) {
18+
isValid = isValid && dfs(root->left, minVal, min((long)root->val, maxVal));
19+
}
20+
if(root->right) {
21+
isValid = isValid && dfs(root->right, max((long)root->val, minVal), maxVal);
22+
}
23+
return isValid;
24+
}
25+
26+
bool isValidBST(TreeNode* root) {
27+
return dfs(root, -(1l << 32), 1l << 32);
28+
}
29+
};

0 commit comments

Comments
 (0)