C++ 在二叉树中找到最大的 BST

标签 c++ algorithm find binary-search-tree binary-search

在二叉树中拥有最大 BST 的方法是什么?最大,我的意思是:最高。

我指的是 this post查找树是否存在的一个很好的实现 BST与否是

bool isBinarySearchTree(BinaryTree * n,
int min=std::numeric_limits<int>::min(),
int max=std::numeric_limits<int>::max()) 
{
     return !n || (min < n->value && n->value < max
     && isBinarySearchTree(n->l, min, n->value)
     && isBinarySearchTree(n->r, n->value, max));
}

很容易实现一个解决方案来查找一棵树是否包含二叉搜索树。我认为以下方法可以做到:

bool includeSomeBST(BinaryTree* n)
{ 
      return includeSomeBST(n->left)  ||  includeSomeBST(n->right) ;

      if(n == NULL)
           return false ; 

      return true ;
}

但是如果我想要最大的 BST 怎么办?这是我的第一个想法,

BinaryTree largestBST(BinaryTree* n)
{ 
      if(isBinarySearchTree(n))
           return n;

      if(!isBinarySearchTree(n->left))
      {
           if(!isBinarySearchTree(n->right))
               if(includeSomeBST(n->right))
                    return largestBST(n->right);

               else if(includeSomeBST(n->left))
                    return largestBST(n->left);

               else
                   return NULL;

           else
               return n->right;
      }
      else 
          return n->left;
}

但实际上并没有告诉最大的。我很难做出比较。它应该如何进行?

谢谢

最佳答案

是的,你的函数 includeSomeBST 是错误的。您只需检查节点 n,n->left 和 n->right,但您必须递归地检查节点。

bool includeSomeBST(BinaryTree* n) {

  if(!isBinarySearchTree(n))
  {

       return includeSomeBST(n->left) || includeSomeBST(n->right);
  }

  if(n==NULL) return false; 
  return true;

关于C++ 在二叉树中找到最大的 BST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12767651/

相关文章:

algorithm - 存储精确集合成员的最有效方式?

algorithm - 在 MATLAB 中查找具有公共(public)重叠区域的多个圆

algorithm - 检测 "bitmap"中的形状

c++ - 从 Qt 应用程序链接到 C++ 静态库

c++ - 如何为字符数组制作模板函数特化?

c++ - 究竟为什么编译器直到运行时才能确定变量的真实类型?

c++ - 保留有关访问状态的信息的想法

c - 在哈希表 C 中查找键

mysql - Rails 中区分大小写的查找

c++ - 在 C++ 中为虚拟函数禁用动态绑定(bind)(虚拟表创建)