98. Verify that the binary search tree

is given a binary tree to determine if it is a valid binary search tree.

Assume that a binary search tree has the following characteristics: The left subtree of the

node contains only the number less than the current node. The right subtree of a node contains only the number greater than the current node. All left and right subtrees themselves must also be binary search trees. Example 1:

Input: 2
   / \
  1   3Export: true

example 2:

入:
    5
   /\
  1   4
     / \3 6
Output: false

Explanation: The input is: [5,1,4,null,null,3,6].      The root node has a value of 5 , but its right child value is 4 . Law 1: Use the nature of its own to solve

/**
 * 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) {
        return valid(root, LONG_MIN, LONG_MAX);
    }
    bool valid(TreeNode* root, long minVal, long maxVal) {
        if(!root) return true;
        if(root->val <= minVal || root->val >= maxVal) {
            return false;
        }
        return valid(root->left, minVal, root->val) && valid(root->right, root->val, maxVal);
    }
};

法二: Because the requirements in the title, left <root < right, so the binary traversal of the binary tree, if the resulting sequence is an ascending sequence, naturally in line with the meaning

/**
 * 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;
        }
        vector<int> res;
        inorder(root, res);
        for(int i = 0; i < res.size() - 1; i++) {
            if(res[i] >= res[i + 1]) {
                return false;
            }
        }
        return true;
    }
    void inorder(TreeNode* root, vector<int>& res) {
        if(!root) {
            return;
        }
        inorder(root->left, res);
        res.push_back(root->val);
        inorder(root->right, res);
    }
};