【发布时间】:2017-03-21 02:33:38
【问题描述】:
我正在尝试解决一个问题,看看二叉树是否是 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));
我不知道我错在哪里,但有些测试失败了。这是一个在线评估,我无法获得失败的测试用例。有人可以帮助我吗?
【问题讨论】:
-
你忘了最后一条语句的返回isBSTUtil(node->left, min, node->data) && isBSTUtil(node->right, node->data, max); ?
-
对不起,这是一个编辑。我错过了。编辑问题。感谢您指出
-
它将在具有单个节点的树上失败,其
data是INT_MAX。
标签: c++ c++11 tree binary-tree binary-search-tree