简体   繁体   English

计算BST节点删除的时间复杂度

[英]Calculating Time Complexity for BST node removal

I have a little difficulty in finding out the average and worst case time complexity. 在找出平均和最坏情况下的时间复杂度方面,我有些困难。 So I made this BST node removal with the following logic 所以我用以下逻辑删除了这个BST节点

When you remove a node in a binary search tree , there are 3 cases 删除二叉搜索树中的节点时,有3种情况

1> The node to delete has no children. That's easy: just release its resources and you're done. Time complexity O(1)

2> The node has a single child node. Release the node and replace it with its child, so the child holds the removed node's place in the tree. Time complexity O(1)

3> The node has two children. Find the right-most child of node's left subtree. Assign its value  to root, and delete this child. **Here time compexity can be maximum O(N)**

To find the node to be deleted can be **maximum O(N)**

So how do you calculate the overall average and worst time complexity?? 那么,您如何计算总体平均时间和最差时间复杂度呢?

In this case, I believe a worst-case complexity will be sufficient to describe the situation. 在这种情况下,我认为最坏情况的复杂性足以描述这种情况。

In order to find the worst-case complexity, simply find the worst case scenario out of the possible three you mentioned (O(n) case). 为了找到最坏情况的复杂性,只需从您提到的三种可能的情况中找出最坏情况(O(n)情况)。 Therefore, the worst-case complexity is O(n). 因此,最坏情况下的复杂度是O(n)。

In some rare cases (such as Quicksort), people choose to describe an average-case complexity as well as a worst-case complexity. 在极少数情况下(例如Quicksort),人们选择描述平均情况下的复杂性以及最坏情况下的复杂性。 In the case of Quicksort, it is because Quicksort is O(n*log(n)) in nearly all cases, and only reduces to O(n^2) in some very rare cases. 就Quicksort而言,这是因为Quicksort在几乎所有情况下均为O(n * log(n)),而在极少数情况下仅减少为O(n ^ 2)。 Therefore, people describe both an average-case, as well as a worst-case complexity. 因此,人们既描述了平均情况,也描述了最坏情况下的复杂性。

In the case of removing a node from a binary search tree, however, removing a leaf node (w/ no children and best case) is does not occur a lot more frequently or a lot less than the removal of a node w/ two children (unless you are developing for a special case). 但是,在从二叉搜索树中删除节点的情况下,删除叶子节点(没有子节点和最好的情况)的发生不会比删除有两个子节点的节点的发生频率更高或更少。 (除非您针对特殊情况进行开发)。

Therefore, the complexity of the removal of a node from a binary search tree is O(n). 因此,从二叉搜索树中删除节点的复杂度为O(n)。

在删除的情况下,平均情况复杂度为O(log(n),因为要找到节点,将花费O(log(n),然后再次删除O(log(n)),因此平均值为O(log(n))+ O(log(n))= O(log(n))最坏的情况显然是O(n)有关更多详细信息,请参见http://en.wikipedia.org/wiki/Binary_search_tree#Deletion

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

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