找到bst中深度最小的叶子节点
需要得到深度最小的叶子节点。我想不出一种不在每个节点中存储附加信息的好方法,请提出建议,非常感谢。
Need to get the leaf node that has minimum depth. I cannot think of a good way to do it without storing additional information in each node, please suggest, thanks very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
强力解决方案是在找到的第一个叶子处终止的广度优先搜索,这比递归更容易迭代实现。
例如,请参阅我对“广度优先与深度优先”的回答中的伪代码 只需向 while 循环添加另一个条件即可。
顺便说一句——这将为您提供最小深度的一片叶子,因为在该深度可能有不止一片叶子。获得全套最小深度叶子有点困难。我想采用迭代深化策略。
找出该节点属于第几级。
三种选择:
首先找到节点,然后在树中搜索它。这听起来很浪费,但第二次搜索只需要访问与关卡一样多的节点,所以它确实很快。
或者,您也可以随时跟踪。您使用三个计数器
levelCounter
、thisLevelCounter
和nextLevelCounter
。每次您到达新节点时,都会递减thisLevelCounter
,当它达到零时,您就会向下移动一个级别,每次您将子节点添加到搜索列表时,都会递增
nextLevelCounter
。每次存储新的子节点增量
nextLevelCounter
最后,迭代深化策略免费为您提供成功级别(哪个迭代找到它......)并且具有相同的性能顺序(尽管稍微更高的乘数)作为广度优先搜索。
The brute force solution is a breadth-first search terminating at the first leaf found, this will be easier to implement iteratively than recursively.
See for instance the pseudo-code in my answer to "Breadth First Vs Depth First" just add another condition to the while-loop.
BTW--This will get you a leaf with the minimum depth, as there may be more than one at that depth. Getting the full set of minimum depth leaves is a little harder. I guess go with an iterative deepening strategy.
Finding out what level that node is one.
Three choices:
Find the node first and the search down the tree for it. It sounds wasteful, but that second search requires visiting only as many nodes as the level, so it really is fast.
Alternately you can keep track as you go. You use three counters
levelCounter
,thisLevelCounter
andnextLevelCounter
. Every time you more to a new node you decrementthisLevelCounter
, and when it hits zero you've moved down a level so doEvery time you add a child node to the search list, increment
nextLevelCounter
.Every time you store a new child node increment
nextLevelCounter
Finally, the iterative deepening strategy gives you the sucess level for free (which iteration finds it...) and has the same order of performance (though a slightly higher multiplier) as the breadth first search.
这里的代码版本(希望我没有错过任何错误检查):
Here code version (hope I didn't miss any error check):