是二叉树 BST,但只有在右子级中才允许重复

Is a Binary tree BST but with duplicates are allowed only in right child

本文关键字:许重复 BST 二叉树      更新时间:2023-10-16

我正在尝试解决一个问题,以查看二叉树是否是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指出。