LeetCode-98. 验证二叉搜索树
给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。
有效 二叉搜索树定义如下:
节点的左子树只包含 小于 当前节点的数。
节点的右子树只包含 大于 当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
class Solution {
public:
// bool fun(TreeNode *root,long lower ,long uper)
// {
// if(!root)return true;
// if(root->val <= lower || root->val >= uper)
// return false;
// return fun(root->left,lower,root->val) && fun(root->right,root->val , uper);
// }
//前序遍历
TreeNode* pre = nullptr;
bool fun1(TreeNode* root){
if(!root)return true;
int left = fun1(root->left);
//因为是前序遍历,所以前一个数一定比后一个数小
if(pre != nullptr && pre->val >= root->val)
return false;
pre = root;
int right = fun1(root->right);
return left && right;
}
bool isValidBST(TreeNode* root) {
return fun1(root);
}
};
执行结果:
通过
执行用时:
8 ms, 在所有 C++ 提交中击败了87.56%的用户
内存消耗:
21.2 MB, 在所有 C++ 提交中击败了30.65%的用户
通过测试用例:
80 / 80
本文介绍了一种验证二叉搜索树是否有效的算法实现。通过递归检查每个节点的值是否在其合法范围内,并确保左右子树也符合二叉搜索树的定义。
896

被折叠的 条评论
为什么被折叠?



