【问题标题】:Counting the number of nodes in a level of a binary search tree计算二叉搜索树级别中的节点数
【发布时间】:2020-08-07 13:25:18
【问题描述】:

正如标题所说,我想计算树的任何给定级别的节点。我已经知道如何制作成员函数来计算树的所有节点,只是不确定如何接近特定级别。这是我尝试过的。任何帮助表示赞赏。

第一个参数是指向用户输入的字符数组。 root 是代表“最旧”节点的私有变量。

int TreeType::GetNodesAtLevel(ItemType* itemArray, int level)
{
    TreeNode* p = root;

    if (itemArray == NULL)
        return;
    if (level == 0)
    {
        cout << p->info << " ";
        return;
    }

    else
    {
        GetNodesAtLevel(itemarray->left, level); //dereference in one and not the other was just testing 
        GetNodesAtLevel(*itemarray->right, level); //neither seems to work
    }
}

【问题讨论】:

  • 碰巧有一种相当简单的方法来做这种事情。只需拿出一张白纸,用简单的英语句子,一步一步地写下来。完成后,schedule an emergency appointment with your rubber duck。我们不会在这里为其他人编写整个程序,但总是将这些问题交给你的橡皮鸭。在您的橡皮鸭批准您提出的行动计划后,只需将您写下的内容直接翻译成 C++。任务完成!

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


【解决方案1】:

做到这一点的方法是使用队列(使用级别顺序遍历 - BFS)。现在按照这个:

取两个变量,count_level 和 count_queue(保持队列中的所有节点)。

对于这样的树:

               A 
              / \
             B   C
            / \   \
           K   L   D
                   /
                  E

最初是 count_level = 0count_queue = 0。现在:

  1. 向队列中添加一个节点(此时A处,将count_queue递增到1)。
  2. 现在,当您找到 count_level = 0 时,请执行此操作 -> count_level = count_queue
  3. 在出队时添加孩子节点,直到 count_level 变为 0。因此,此时请执行以下步骤 2,这将为您提供低于刚刚处理的节点的数量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-04
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 2015-05-14
    相关资源
    最近更新 更多