简体   繁体   English

平衡二分搜索树中特定级别的节点数是多少?

[英]What is the number of nodes at a particular level in a balanced binary search tree?

I was asked this question in a phone screen interview and I was not able to answer it. 在电话屏幕访问中有人问我这个问题,但我无法回答。 For example, in a BST, I know that the maximum number of nodes is given by 2^h (assuming the root node at height = 0) 例如,在BST中,我知道最大节点数由2 ^ h给出(假设根节点的高度= 0)

I wanted to ask, is there a similar mathematical outcome for a balanced binary search tree as well (For AVL, Red Black trees?), ie the number of nodes at a particular level k. 我想问,平衡二叉搜索树(对于AVL,红黑树)是否也有类似的数学结果,即特定级别k的节点数。

Thanks! 谢谢!

A balanced binary tree starts with one node, which has two descendants. 平衡的二叉树从一个节点开始,该节点有两个后代。 Each of those then has two descendants again. 然后,每个人又有两个后代。 So there will be 1, 2, 4, 8 and so on nodes per level. 因此,每个级别将有1、2、4、8等个节点。

As a formula you can use 2^(level-1) . 作为公式,您可以使用2^(level-1) The last row might not be completely full, so it can have less elements. 最后一行可能未完全填满,因此可以包含更少的元素。

As the balancing step is costly, implementations usually do not rebalance after every mutation of the tree. 由于平衡步骤的成本很高,因此在每次树变种之后,实现通常都不会重新平衡。 They will rather apply a heuristic to find out when a rebalancing will make the most sense. 他们宁愿运用启发式方法来找出何时进行重新平衡才是最有意义的。 So in practice, levels might have less nodes than if the tree were perfectly balanced and there might be additional levels from nodes being inserted in the wrong places. 因此,在实践中,与树完全平衡相比,级别可能具有更少的节点,并且从错误位置插入的节点可能还会有其他级别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM