-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathValidate Binary Search Tree.cpp
More file actions
47 lines (37 loc) · 1.06 KB
/
Validate Binary Search Tree.cpp
File metadata and controls
47 lines (37 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
long getMax(TreeNode* root)
{
if(root==NULL)
return LONG_MIN;
TreeNode* temp=root;
while(temp->right!=NULL)
temp=temp->right;
return temp->val;
}
long getMin(TreeNode* root)
{
if(root==NULL)
return LONG_MAX;
TreeNode* temp=root;
while(temp->left!=NULL)
temp=temp->left;
return temp->val;
}
bool isValidBST(TreeNode* root) {
if(root==NULL)
return true;
if(root->left==NULL && root->right==NULL)
return true;
return (isValidBST(root->left) && isValidBST(root->right) && (getMax(root->left) < root->val) && (getMin(root->right)>root->val));
}
};