# 98. Validate Binary Search Tree 验证二叉搜索树

@TOC

## # 题目描述

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.
``````

## # 解题方法

### # 递归

``````# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.valid(root, float('-inf'), float('inf'))

def valid(self, root, min, max):
if not root: return True
if root.val >= max or root.val <= min:
return False
return self.valid(root.left, min, root.val) and self.valid(root.right, root.val, max)
``````

C++代码如下：

``````/**
* 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:
bool isValidBST(TreeNode* root) {
if (!root)
return true;
return helper(root, LONG_MIN, LONG_MAX);
}

bool helper(TreeNode* root, long minVal, long MaxVal) {
if (!root)
return true;
if (root->val >= MaxVal || root->val <= minVal)
return false;
return helper(root->left, minVal, root->val) && helper(root->right, root->val, MaxVal);
}
};
``````

Java代码如下：

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
return isValid(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean isValid(TreeNode root, long min, long max){
if(root == null){
return true;
}
long mid = root.val;
if(mid <= min || mid >= max){
return false;
}
return isValid(root.left, min, mid) && isValid(root.right, mid, max);
}
}
``````

### # BST的中序遍历是有序的

python代码如下：

``````# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
res = []
self.inOrder(root, res)
return res == sorted(res) and len(res) == len(set(res))

def inOrder(self, root, res):
if not root: return []
l = self.inOrder(root.left, res)
if l:
res.extend(l)
res.append(root.val)
r = self.inOrder(root.right, res)
if r:
res.extend()
``````

``````/**
* 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:
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);
}
};
``````

## # 日期

2017 年 4 月 17 日 2018 年 3 月 23 日 —— 科目一考了100分哈哈哈哈～嗝～ 2019 年 1 月 19 日 —— 有好几天没有更新文章了