c++ - 是一个二叉树 BST 但只有右 child 才允许重复

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

我正在尝试解决一个问题,看看二叉树是否是 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++ - 是一个二叉树 BST 但只有右 child 才允许重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42917436/

相关文章:

c++ - 将项目分为.h和.cpp

c++ - C 和 C++ 中类的区别

sql - 树结构查询中逻辑或的完全外部连接的替代方法

javascript - 如何在客户端生成父/子嵌套?

javascript - Qt Qml Javascript - 在哪里使用哪个?

c++ - 无法从端口 2368 (Linux) C 接收 UDP 流

c++ - 有没有办法在 C++11 中传递嵌套初始化列表来构造二维矩阵?

c++ - std 原子同步和非原子变量 : not a stale data?

c++11 to_string 与 code::blocks -std=c++11 flag already selected

python - 跟踪和更新递归函数中的值