标签: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