[LeetCode_98]Validate Binary Search Tree

题目链接

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

posted on 2019-01-24 19:14  coding_gaga  阅读(91)  评论(0编辑  收藏  举报

导航