码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode_98]Validate Binary Search Tree

时间:2019-01-24 20:15:37      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:false   eem   tree   ret   代码   str   als   binary   http   

题目链接

https://leetcode.com/problems/validate-binary-search-tree/

题意

判断给定树是否是BST

思路

根据定义判断。递归。

代码

class Solution {
public:
    bool isValidBST(TreeNode* root) {
        if(!root){return true;}
        else{
            return isBST(root)->validBST;
        }
    }
    
private:
    struct TreeMes{
        bool validBST;
        int max;
        int min;
    };
    
    TreeMes* isBST(TreeNode* root){
        TreeMes *treeMes=new TreeMes;
        if(!root->left&&!root->right){
            treeMes->max=root->val;
            treeMes->min=root->val;
            treeMes->validBST=true;
            return treeMes;
        }
        else if(!root->left){
            TreeMes *rTreeMes=isBST(root->right);
            if(rTreeMes->validBST&&(rTreeMes->min>root->val)){
                treeMes->min=root->val;
                treeMes->max=rTreeMes->max;
                treeMes->validBST=true;
            }
            else{treeMes->validBST=false;}
            delete rTreeMes;
            return treeMes;
        }
        else if(!root->right){
            TreeMes *lTreeMes=isBST(root->left);
            if(lTreeMes->validBST&&(lTreeMes->max<root->val)){
                treeMes->max=root->val;
                treeMes->min=lTreeMes->min;
                treeMes->validBST=true;
            }
            else{treeMes->validBST=false;}
            delete lTreeMes;
            return treeMes;
        }
        else{
            TreeMes *lTreeMes=isBST(root->left);
            TreeMes *rTreeMes=isBST(root->right);
            if(lTreeMes->validBST&&(lTreeMes->max<root->val)&&rTreeMes->validBST&&(rTreeMes->min>root->val)){
                treeMes->min=lTreeMes->min;
                treeMes->max=rTreeMes->max;
                treeMes->validBST=true;
            }
            else{treeMes->validBST=false;}
            delete lTreeMes;
            delete rTreeMes;
            return treeMes;
        }
    }
};

[LeetCode_98]Validate Binary Search Tree

标签:false   eem   tree   ret   代码   str   als   binary   http   

原文地址:https://www.cnblogs.com/coding-gaga/p/10316365.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!