bool isValidBST(struct TreeNode* root ) {
    // write code here

    if (root == NULL)
        return true;

    struct TreeNode* leftmax = root->left, *rightmin = root->right;
    if (leftmax != NULL) {
        while (leftmax->right != NULL)
            leftmax = leftmax->right;
        if (leftmax->val > root->val )
            return false;
    }
    if (rightmin != NULL) {
        while (rightmin->left != NULL)
            rightmin = rightmin->left;
        if (rightmin->val < root->val)
            return false;
    }

    if (root->left == NULL || (root->left->val < root->val &&
                               isValidBST(root->left )) )
        if (root->right == NULL || (root->right->val > root->val &&
                                    isValidBST(root->right )) )
            return true;

    return false;
}