【问题标题】:Recursive function to count number of nodes with two children in BST用于计算 BST 中具有两个子节点的节点数的递归函数
【发布时间】:2020-03-18 09:49:55
【问题描述】:

我需要实现这个递归函数,它将以 BST 为根,并递归计算其中包含两个子节点的节点数,但我不确定我的逻辑是否正确?

我的逻辑是:

  1. 如果叶子或空,我们返回 0
  2. 您检查一个节点是否有两个孩子,我们添加一个并在其左右孩子上再次调用
  3. 否则,如果一个节点没有两个子节点,则在其左右子树上调用而不添加

这是我的函数实现 ps:假设 BinarySearchTree 类中的所有内容都已实现:

int count(BinarySearchTree *root  )
{
    if(root== nullptr)
    {
        return 0;
    }

    if(root->right != nullptr and root->left!= nullptr)
    {
        return  1+count(root->right)+count(root->left);
    }

    count(root->right);
    count(root->left);

}

【问题讨论】:

  • 你真的没有问题,你想知道如何修复你的代码吗?
  • 你有什么问题?
  • 对不起,我的逻辑是否正确
  • 在你暴露的代码中,有一条不归路。 (我相信你的编译器会告诉你同样的。)
  • 你能添加一些示例输入和预期输出吗?我对包含或排除子节点计数有点困惑。

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


【解决方案1】:

即使您的节点没有两个子节点,您也需要汇总计数。 if 之后的两次 count 调用基本上没有被使用。 你可以这样修复它:

int count(BinarySearchTree *root  )
{
    if (root== nullptr)
    {
        return 0;
    }

    int countForThisNode = root->right != nullptr and root->left!= nullptr;
    return countForThisNode + count(root->right) + count(root->left);
}

在这种情况下,countForThisNode 对于您要计数的节点为 1,否则为 0。无论如何,所有其他节点都会添加到结果中。

我希望这是您要的信息!

【讨论】:

  • 优雅漂亮,我的实现是否正确?
  • 你打算只计算一个有两个孩子的节点吗?这是我从int countForThisNode = root->right != nullptr and root->left!= nullptr;读到的。
  • @Scheff 是的,只有具有 2 个子节点的节点才应计入
  • @Matcha_boy98 我不知何故错过了其中有两个孩子的节点数。 ;-)
  • @Matcha_boy98 您的实现不计算具有两个子节点的节点,但是在从根节点开始的过程中,节点只有一个子节点(这在 BST 中是一种可能的情况)。此外,您的程序甚至会崩溃,因为您没有从下半场返回。你至少可以在那里做return count(root->right) + count(root->left);
【解决方案2】:

您的函数具有未定义的行为,因为可以将控件转移到右大括号而不返回任何内容。

    count(root->right);
    count(root->left);

}

对于初学者,因为列表没有改变,参数应该有限定符const

函数可以通过以下方式更简单地定义

unsigned int count( const BinarySearchTree *root  )
{
    return root == nullptr ? 0
                           : ( root->left && root->right ) + count( root->left ) 
                                                           + count( root->right );
}

【讨论】:

    【解决方案3】:

    实现此功能的简单方法:

    • 从一个标准节点枚举开始(可以是前缀、中缀、后缀,无所谓);

    • 修改它,以便在每个节点上,如果有两个子节点,则递增计数器。

    请注意,您需要查看整个树,因为它的一部分可能通过单子节点到达。


    visit(root):
      if root.left != null:
          visit(root.left)
      if root.right != null:
          visit(root.right)
    

    变成

    visit(root):
      count= root.left != null and root.right != null
      if root.left != null:
          count+= visit(root.left)
      if root.right != null:
          count+= visit(root.right)
      return count
    

    【讨论】:

      猜你喜欢
      • 2017-08-22
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 2021-09-03
      • 1970-01-01
      • 2018-10-31
      • 2017-08-09
      相关资源
      最近更新 更多