【问题标题】:Is a Binary tree BST but with duplicates are allowed only in right child是二叉树 BST,但仅在右孩子中允许重复
【发布时间】: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); ?
  • 对不起,这是一个编辑。我错过了。编辑问题。感谢您指出
  • 它将在具有单个节点的树上失败,其 dataINT_MAX

标签: c++ c++11 tree binary-tree binary-search-tree


【解决方案1】:

试试下面的代码:

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 在某些平台上也是 4bytes 并且还不够。 感谢@Bernard 指出。

【讨论】:

  • 哪个现代 C++ 编译器对 longint 有不同的大小?我所知道的每个现代编译器(包括 GCC、Clang、MSVC 和 ICC)都将它们都视为 4 字节,无论您是编译 32 位还是 64 位。
  • x64 平台上的 gcc 版本 5.4.0,long 为 8 字节,int 为 4 字节。感谢您指出。你是对的,一些平台 long 和 int 具有相同的大小。
  • 哦,我没有意识到 GCC 会这样做。也许OP应该使用long long
  • 显然,GCC 只在 Linux 上这样做:stackoverflow.com/questions/12794603/…
  • 对于 long 和 int 的参考。这么长时间是最好的做法。 en.cppreference.com/w/cpp/language/types
猜你喜欢
  • 2014-07-09
  • 1970-01-01
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
  • 2010-09-22
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
相关资源
最近更新 更多