Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
According to the definition of BST. left is smaller than root, right is larger than root.
I remembered that it was INT_MAX, but it seems right now, leetcode can only accept LONG_MAX....hmm....
static bool isValidBST(TreeNode* root, long long int maxRange, long long int minRange) {
if(!root) return true;
if(root->val >= maxRange || root->val <= minRange) return false;
return isValidBST(root->left, root->val, minRange) && isValidBST(root->right, maxRange, root->val);
}
bool isValidBST(TreeNode* root) {
if(!root) return true;
return isValidBST(root, LONG_MAX, LONG_MIN);
}
Maybe it is a good idea to try DFS?
本文介绍了一种通过递归方法验证二叉树是否为有效二叉搜索树的方法。根据二叉搜索树的定义,左子树的所有节点值小于根节点值,右子树的所有节点值大于根节点值,并且左右子树也必须是二叉搜索树。文章提供了一个具体的C++实现示例。
511

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



