algorithm - 给定的二叉树是否完整

标签 algorithm data-structures

<分区>

给定一个二叉树,编写一个函数来检查给定的二叉树是否是完全二叉树。

完全二叉树是一棵二叉树,其中除了可能的最后一层外,每一层都被完全填充,并且所有节点都尽可能地靠左。来源:wikipedia

My approach is do BFS using queue and count the no of nodes. Run a loop till the queue is not null but break once you find one of the below condition holds good:

  1. left node is not present for a node
  2. left node is present but right node is not present.

Now we can compare the count that we get from the above approach and the original count of the nodes in the tree. If both equal then complete binary tree else not.

请告诉我这个方法是否正确。谢谢。

这个问题和this的问题是一样的.但我想在这里验证我的方法。

编辑: 该算法由下面的@Boris Strandjev验证。我觉得这是 net 中可用的一些算法中最容易实现的算法。如果您不同意我的主张,我深表歉意。

最佳答案

您的算法应该可以解决问题。

您使用 BFS 所做的完全等同于绘制树,然后用手指从上到下和从左到右追踪节点。第一次无法继续时,请停止用手指追踪。如果你没有统计所有的节点,那么这个结构显然不符合预期。

关于algorithm - 给定的二叉树是否完整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18159884/

相关文章:

algorithm - 以下循环的运行时间

C# 无法链接 LinkedList 中的节点

c++ - C 中的链表

java - 循环链表和迭代器 API 缺乏确定性

python - 如何使用 Python 从链表中删除给定节点

c++ - 如何计算2的10000000次方

algorithm - 网络流中的 'increasing Edge'

algorithm - matlab中高效的密集对角矩阵生成

python - 提高算法的清晰度和效率

java - 分支 & 绑定(bind)错误 : Node1 cannot be cast to java. lang.Comparable