【问题标题】:getting the number of nodes in a binary search tree获取二叉搜索树中的节点数
【发布时间】:2013-03-12 21:55:24
【问题描述】:

所以我正在研究一种获取二叉搜索树中节点数的方法,当我有 3 个节点时,它给我 3,但如果我做 5 它给我 4,我需要改变什么?

int BinaryTree::size(int count, Node *leaf) const
{
    if(leaf != NULL)//if we are not at a leaf
    {
        size(count + 1, leaf->getLeft());//recurisvly call the function and increment the count
        size(count + 1, leaf->getRight());
    }
    else
    {
        return count;//return the count
    }

}

【问题讨论】:

  • 要求人们发现代码中的错误并不是特别有效。您应该使用调试器(或添加打印语句)来隔离问题,方法是跟踪程序的进度,并将其与您期望发生的情况进行比较。一旦两者发生分歧,那么您就发现了您的问题。 (然后如果有必要,你应该构造一个minimal test-case。)
  • 您在 if 的真实分支中缺少返回语句
  • if 语句的第一个块中没有返回值。你要返回什么值?

标签: c++ tree nodes


【解决方案1】:
int BinaryTree::size(Node *leaf) const 
{
    if(leaf == NULL) { //This node doesn't exist. Therefore there are no nodes in this 'subtree'
        return 0;
    } else { //Add the size of the left and right trees, then add 1 (which is the current node)
        return size(leaf->getLeft()) + size(leaf->getRight()) + 1;
    }
}

虽然这是一种不同的方法,但我发现它比您的方法更容易阅读。

【讨论】:

    【解决方案2】:

    其他人已经提出了正确的算法。我只是解释一下为什么你的算法不起作用。

    您的算法背后的逻辑似乎是:保持运行计数值。如果叶子为空,则它没有子节点,因此返回计数,如果叶子不为空,则向下递归子节点。

    这是倒退的。因为你需要通过引用而不是值来传递你的 int,然后如果它为 null 则不递增,如果它不为 null 则递增,然后递归。

    所以你最初的想法可以通过一些修改来实现,但 Nick Mitchinson 和 arrows 有更好的方法。这是您的算法已修复,因此可以正常工作:

    int BinaryTree::size(Node *leaf, int& count=0) const
    {
        if(leaf != NULL)//if we are not at a leaf
        {
            count++;
            size(leaf->getLeft(), count);//recurisvly call the function and increment the count
            size(leaf->getRight(), count);
        }
    
        return count;//return the count
    }
    

    但同样,有更好的方法来写这个。其他答案显示了它们。

    【讨论】:

      【解决方案3】:
      int BinaryTree::size(Node *n) const
      {
          if(!n) 
              return 0;
          else
              return size(n->getLeft()) + 1 + size(n->getRight()); 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多