验证二叉搜索数(98)
98. 验证二叉搜索树 - 力扣(LeetCode)
解法:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root)
{
if ((root == nullptr) ||
(root->left == nullptr && root->right == nullptr))
{
return true;
}
//考虑到Node.val 的取值范围:-2exp(31) <= Node.val <= 2exp(31) - 1,bound代表二叉搜索数一个节点需要满足的值的范围,所以搜索二叉树初始化的最小值和最大值:
std::pair<int64_t, int64_t> bound = std::make_pair(int64_t(numeric_limits<int32_t>::min()) - 1, int64_t(numeric_limits<int32_t>::max()) + 1);
return isValidBSTCore(root, bound);
}
bool isValidBSTCore(TreeNode* root, std::pair<int64_t, int64_t> bound)
{
if (root == nullptr) {
return true;
}
//前序遍历,先访问当前节点
if (root->val > bound.first && root->val < bound.second )
{
//访问左子树,以及计算其取值范围 && 访问又子树 以及计算其取值范围
return isValidBSTCore(root->left, std::make_pair(bound.first, std::min(int64_t(root->val),bound.second))) && isValidBSTCore(root->right, std::make_pair(std::max(int64_t(root->val), bound.first), bound.second));
}else {
return false;
}
}
};
总结:
计算时间复杂度O(N),其空间复杂度O(N),具体算法如上述代码和注释。