/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool check(TreeNode *root,int mmin,int mmax)
{
if(root==NULL)
return true;
if(root->val<mmax && root->val>mmin)
{
return
(check(root->left,mmin,min(root->val,mmax))//递归判断,递归时传入两个参数,一个是左界,一个是右界,节点的值必须在两个界的中 间,同时在判断做子树和右子树时更新左右界。
&&check(root->right,max(root->val,mmin),mmax));
}
return false;
}
bool isValidBST(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int mmin=INT_MIN;
int mmax=INT_MAX;
return check(root,mmin,mmax);
}
};
【leetcode】Validate Binary Search Tree
最新推荐文章于 2019-05-28 19:29:53 发布