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

判断是不是二叉搜索树

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) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return bool布尔型
     */
    bool isValidBST(TreeNode* root) {
        // write code here
        // 递归判断是否符合
       
        auto [isTree, maxValue] = GetMax(root);
        return isTree;
    }

    pair<bool, int> GetMax(TreeNode* root){
        // 返回该分支最大值和是否是二叉搜索树的pair
        // 递归判断是否符合
        int max;
        bool isValidLeft = true;
        max = root->val;
        if(root->left != nullptr){
            auto [isLeft, maxLeft] = GetMax(root->left);
            cout<<"left,"<<maxLeft<<endl;
            if(root->val > maxLeft&&isLeft){
                isValidLeft = true;
            }
            else{
                isValidLeft = false;
            }
        }
        bool isValidRight;
        
        if(root->right != nullptr){
            auto [isRight, maxRight] = GetMax(root->right);
            cout<<"right,"<<maxRight<<endl;
            if(root->val<maxRight&&isRight){
                isValidRight= true;
                max = maxRight;
            }
            else{
                isValidLeft = false;
            }
        }
        // 当前内容展示
        if(isValidLeft&&isValidLeft){
            return pair(true, max);
        }
        else{
            return pair(false, max);
        }
        
    }
};

全部评论

相关推荐

06-25 09:33
厦门大学 Java
球球别拷打俺了:现在日常估计没啥hc了,等到八月多估计就慢慢有了。双九✌🏻不用焦虑的
投递快手等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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