[英]Time Efficiency of Binary Search Tree
for the time efficiency of inserting into binary search tree, 为了提高插入二分搜索树的时间效率,
I know that the best/average case of insertion is O(log n), where as the worst case is O(N). 我知道插入的最佳/平均情况是O(log n),而最坏的情况是O(N)。
What I'm wondering is if there is any way to ensure that we will always have best/average case when inserting besides implementing an AVL (Balanced BST)? 我想知道的是,除了实现AVL(Balanced BST)之外,是否还有其他方法可以确保插入时始终保持最佳/平均情况?
Thanks! 谢谢!
There is no guaranteed log n
complexity without balancing a binary search tree. 不平衡二进制搜索树就无法保证log n
复杂性。 While searching/inserting/deleting, you have to navigate through the tree in order to position yourself at the right place and perform the operation. 搜索/插入/删除时,您必须在树中导航才能将自己放置在正确的位置并执行操作。 The key question is - what is the number of steps needed to get at the right position? 关键问题是-达到正确位置需要多少步骤? If BST is balanced, you can expect on average 2^(i-1)
nodes at the level i
. 如果BST是平衡的,则可以平均预期将2^(i-1)
节点的级别i
。 This further means, if the tree has k
levels ( k
is called the height of tree), the expected number of nodes in the tree is 1 + 2 + 4 + .. + 2^(k-1) = 2^k - 1 = n
, which gives k = log n
, and that is the average number of steps needed to navigate from the root to the leaf. 这进一步意味着,如果树具有k
级别( k
称为树的高度 ),则树中的预期节点数为1 + 2 + 4 + .. + 2^(k-1) = 2^k - 1 = n
,得出k = log n
,这是从根导航到叶所需的平均步骤数。
Having said that, there are various implementations of balanced BST. 话虽如此,平衡BST有多种实现方式。 You mentioned AVL, the other very popular is red-black tree , which is used eg in C++ for implementing std::map
or in Java for implementing TreeMap
. 您提到了AVL,另一个非常流行的是红黑树 ,例如在C ++中用于实现std::map
或在Java中用于实现TreeMap
。
The worst case, O(n)
, can happen when you don't balance BST and your tree degenerates into a linked list. 最糟糕的情况是O(n)
,当您不平衡BST并且树退化为链接列表时,可能会发生。 It is clear that in order to position at the end of the list (which is a worst case), you have to iterate through the whole list, and this requires n
steps. 显然,为了定位在列表的末尾(这是最坏的情况),您必须遍历整个列表,这需要n
步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.