简体   繁体   中英

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

When you remove a node in a binary search tree , there are 3 cases

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). Therefore, the worst-case complexity is O(n).

In some rare cases (such as Quicksort), people choose to describe an average-case complexity as well as a worst-case complexity. 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. 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(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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