# 98. Validate Binary Search Tree

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/validate-binary-search-tree/description/

> 内容描述

```
Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:

Input:
    2
   / \
  1   3
Output: true
Example 2:

    5
   / \
  1   4
     / \
    3   6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
             is 5 but its right child's value is 4.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(N)******


中序遍历一次，看看list是否严格满足递增

```python
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def inorder(root):
            if not root:
                return
            inorder(root.left)
            res.append(root)
            inorder(root.right)
            
        res = []
        if not root:
            return True
        inorder(root)
        for i in range(1, len(res)):
            if res[i].val <= res[i-1].val:
                return False
        return True
```

> 思路 2
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******


以前做过这道题，valid binary tree，需要check两件事：


```
   			10
   		   /  \
   		  7   20
   		      / \ 
   		     5  40 
```


- node.left.val < node.val
	- right subtree of left child, value < node.val
- node.right.val > node.val
	- left subtree of the right child, value > node.val


wikipedia上有伪码：

```
truct TreeNode {
    int key;
    int value;
    struct TreeNode *left;
    struct TreeNode *right;
};

bool isBST(struct TreeNode *node, int minKey, int maxKey) {
    if(node == NULL) return true;
    if(node->key < minKey || node->key > maxKey) return false;
    
    return isBST(node->left, minKey, node->key) && isBST(node->right, node->key, maxKey);
}


if(isBST(root, INT_MIN, INT_MAX)) {
    puts("This is a BST.");
} else {
    puts("This is NOT a BST!");
}
```

实际上就是每次往下看，node都确保被夹在一个范围。


```python
class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def valid(root, smallest, largest):
            if not root:
                return True
            if smallest >= root.val or largest <= root.val:
                return False
            return valid(root.left, smallest, root.val) and valid(root.right, root.val, largest)
        if not root:
            return True
        return valid(root, -sys.maxsize, sys.maxsize)
```



