gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:57:00 24 4
gpt4 key购买 nike

<分区>

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

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

My approach is do BFS using queue and count the no of nodes. Run aloop till the queue is not null but break once you find one of thebelow 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 andthe original count of the nodes in the tree. If both equal thencomplete binary tree else not.

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

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com