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

判断是不是二叉搜索树

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

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
#include <utility>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return bool布尔型
     */
    bool isValidBST(TreeNode* root) {
        // write code here
        return check(root).second;
    }
    pair<pair<TreeNode*,TreeNode*>,bool> check(TreeNode* root){
        bool issearch = true;
        pair<pair<TreeNode*,TreeNode*>,bool> Left;
        pair<pair<TreeNode*,TreeNode*>,bool> Right;
        TreeNode* min=nullptr;
        TreeNode* max=nullptr;
        if(root == nullptr)
            return make_pair(make_pair(nullptr,nullptr), true);
        if(root->left!=nullptr){
            Left = check(root->left);
            if(Left.second == false)
                return make_pair(make_pair(min,max), false);
            if(Left.first.second->val>=root->val)
                return make_pair(make_pair(min,max), false);
            min = Left.first.first;
        }else 
            min = root;
        if(root->right!=nullptr){
            Right = check(root->right);
            if(Right.second == false)
                return make_pair(make_pair(min,max), false);
            if(Right.first.first->val<=root->val)
                return make_pair(make_pair(min,max), false);
            max = Right.first.second;
        }else 
            max = root;
        return make_pair(make_pair(min,max), true);
    }
};

这道题一开始踩了一个坑,就是只递归判断当前结点是不是比左结点大,右结点小,,但是有可能出现的bug是右子树中存在比自己小的结点(左子树也一样),因此必须求出左右子树中的最大最小。

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务