/**
 * struct TreeNode {
 *  int val;
 *  struct TreeNode *left;
 *  struct TreeNode *right;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param root TreeNode类
 * @return bool布尔型
 */

bool isValidBSTHelperLEFT(struct TreeNode* root, int val) {
    if (root == NULL) return true;
    if (!isValidBSTHelperLEFT(root->left, val)) return false;
    if (!isValidBSTHelperLEFT(root->right, val)) return false;
    if (root->left != NULL && (root->left->val > root->val || root->left->val > val)) {
        return false;
    } else if (root->right != NULL && (root->right->val < root->val || root->right->val > val)) {
        return false;
    }
    return true;
}
bool isValidBSTHelperRIGHT(struct TreeNode* root, int val) {
    if (root == NULL) return true;
    if (!isValidBSTHelperRIGHT(root->left, val)) return false;
    if (!isValidBSTHelperRIGHT(root->right, val)) return false;
    if (root->left != NULL && (root->left->val > root->val || root->left->val < val)) {
        return false;
    } else if (root->right != NULL && (root->right->val < root->val || root->right->val < val)) {
        return false;
    }
    return true;
}

bool isValidBST(struct TreeNode* root ) {
    // write code here
    if(root == NULL) return true;
    if(root->left != NULL && root->left->val > root->val) {
        return false;
    }
    if(root->right != NULL && root->right->val < root->val) {
        return false;
    }
    if(!isValidBSTHelperLEFT(root->left, root->val) || !isValidBSTHelperRIGHT(root->right, root->val)) return false;
    return isValidBST(root->left) && isValidBST(root->right);

}