# 98. Validate Binary Search Tree

{% embed url="<https://leetcode.com/problems/validate-binary-search-tree/>" %}

验证BST，只需要recursively验证当前节点的值是否在合格区间内。

或者利用BST性质（inorder遍历是ascending的），只需要把当前值与prev比较即可。

{% tabs %}
{% tab title="range check" %}

```python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isValidBST(self, root: TreeNode) -> bool:
        return self.checkNode(root, float("-inf"), float("inf"))
    
    def checkNode(self, node, lower, upper) -> bool:
        if not node: return True
        if node.val <= lower or node.val >= upper:
            return False
        else:
            return (self.checkNode(node.left, lower, node.val) and self.checkNode(node.right, node.val, upper))
```

{% endtab %}

{% tab title="BST性质" %}

```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) {
        prev_ = nullptr;
        return inorder(root);
    }
private:
    TreeNode *prev_;
    bool inorder(TreeNode* root) {
        if (!root) return true;
        if (!inorder(root->left)) return false;
        if (prev_ && root->val <= prev_->val) return false;
        prev_ = root;
        return inorder(root->right);
    }
};
```

{% endtab %}
{% endtabs %}
