题解 | #判断是不是二叉搜索树#

判断是不是二叉搜索树

https://www.nowcoder.com/practice/a69242b39baf45dea217815c7dedb52b

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;
}

全部评论

相关推荐

评论
3
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务