是二叉树 BST,但只有在右子级中才允许重复
Is a Binary tree BST but with duplicates are allowed only in right child
我正在尝试解决一个问题,以查看二叉树是否是BST。我找到的解决方案是没有重复项的二叉树。Geeksforgeeks link
int isBST(struct node* node)
{
return(isBSTUtil(node, INT_MIN, INT_MAX));
}
/* Returns true if the given tree is a BST and its
values are >= min and <= max. */
int isBSTUtil(struct node* node, int min, int max)
{
/* an empty tree is BST */
if (node==NULL)
return 1;
/* false if this node violates the min/max constraint */
if (node->data < min || node->data > max)
return 0;
/* otherwise check the subtrees recursively,
tightening the min or max constraint */
return
isBSTUtil(node->left, min, node->data-1) && // Allow only distinct values
isBSTUtil(node->right, node->data+1, max); // Allow only distinct values
}
对于重复项,我所做的只是更改了以下部分。同样只能在右侧子节点中找到重复项,即左侧子节点中的所有子节点都应小于当前节点,但右侧子节点可能具有与父节点相同的值。
if (node->data < min || node->data >= max)
return 0;
return(isBSTUtil(node->left, min, node->data) &&
isBSTUtil(node->right, node->data, max));
我不知道我错在哪里,但有些测试失败了。这是一个在线评估,我无法获得失败的测试用例。有人可以在这方面帮助我吗?
尝试以下代码:
int isBST(struct node* node)
{
return(isBSTUtil(node, INT_MIN, INT_MAX));
}
/* Returns true if the given tree is a BST and its
values are >= min and <= max. */
int isBSTUtil(struct node* node, long long min, long long max)
{
/* an empty tree is BST */
if (node==NULL)
return 1;
/* false if this node violates the min/max constraint */
if (node->data < min || node->data > max)
return 0;
/* otherwise check the subtrees recursively,
tightening the min or max constraint */
return
isBSTUtil(node->left, min, long long (node->data) - 1) && /*left smaller*/
isBSTUtil(node->right, node->data, max); /*right can equal or greater*/
}
为避免下溢,应使用long long而不是int。在某些平台上,long 也是 4 字节,这还不够。感谢您@Bernard指出。
相关文章:
- C/C++编译器通常会删除重复的库吗
- 整数不会重复超过随机数
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- C++避免重复声明的语法是什么
- 具有重复类型的C++可变模板
- 使用函数"remove"删除重复元素
- 如何从多映射中删除特定的重复项
- 我想做一个彼此不同但重复出现的数字
- 如何在BST的这个简单递归实现中消除警告
- 使用for循环检查数组中的重复项
- 输出没有重复元素的动态数组(收缩数组)C++
- 数组中最大的非重复元素
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 如何计算多映射中重复对的数量
- 我收到同义重复编译器错误。我应该如何修复"类型"X"的参数与类型"X"的参数不兼容?
- 是二叉树 BST,但只有在右子级中才允许重复
- C++:计算BST中的重复项
- 从BST中删除重复元素
- C++:删除BST中的一个节点,要么得到一个seg错误,要么重复节点