【问题标题】:How to count number of leaf nodes in a binary tree using queue?如何使用队列计算二叉树中叶节点的数量?
【发布时间】:2017-03-30 09:06:36
【问题描述】:

我正在学习 c 语言。使用递归计算二叉树中的叶节点很简单,但我们如何使用队列来计算呢?

【问题讨论】:

  • “叶节点”到底是什么意思?你想做什么?你被困在哪里了?
  • 二叉树中的叶节点。
  • 请用您的代码更新问题。
  • 使用while 循环跟随左节点,将任何右节点放入队列中。当你到达叶子节点时,从队列中的一个节点继续,直到队列为空。
  • 左节点子树中的叶子如何计算?

标签: c


【解决方案1】:

使用队列对树进行广度优先遍历,并检查特定节点是否有两个子节点NULL

伪代码:

queue = [root]
count = 0
while !queue.empty():
    current_node = queue.dequeue()
    if (current_node.left == NULL) and (current_node.right == NULL):
        count += 1
        continue
    if (current_node.left != NULL):
        queue.enqueue(current_node.left)
    if (current_node.right != NULL):
        queue.enqueue(current_node.right)

print count

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
相关资源
最近更新 更多