---
tags: leetcode
---
# [98. Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)
---
# My Solution
## The Key Idea for Solving This Coding Question
## C++ Code
```cpp=
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode *root) {
return isValidBST(root, LONG_MIN, LONG_MAX);
}
private:
bool isValidBST(TreeNode *root, long lowerBound, long upperBound) {
if (root == nullptr) {
return true;
}
if (root->val <= lowerBound || upperBound <= root->val) {
return false;
}
return isValidBST(root->left, lowerBound, root->val) &&
isValidBST(root->right, root->val , upperBound);
}
};
```
## Time Complexity
$O(n)$
$n$ is the number of nodes in the binary tree referred by `root`.
## Space Complexity
$O(H)$
$H$ is the height of the binary tree referred by `root`.
# Miscellane
<!--
# Test Cases
```
[2,1,3]
```
```
[5,1,4,null,null,3,6]
```
* Wrong Answer:
```
[2,2,2]
```
* Wrong Answer:
```
[32,26,47,19,null,null,56,null,27]
```
* Wrong Answer:
```
[1,null,1]
```
```
[1]
```
```
[10,5,15,null,null,6,20]
```
```
[1,2,3,4,null,null,5]
```
```
[3,9,20,null,null,15,7]
```
```
[4,2,7,1,3]
```
```
[18,2,22,null,null,null,63,null,84,null,null]
```
```
[2147483647]
```
-->