in DS edited by
2,993 views
31 votes
31 votes

Consider the binary tree in the figure below:

Outline a procedure in Pseudo-code to delete an arbitrary node from such a binary tree with $n$ nodes that preserves the structures. What is the worst-case time complexity of your procedure?

in DS edited by
3.0k views

2 Answers

61 votes
61 votes
Best answer

By looking at the values it is clear that It is a Min-Heap Data structures. We know that Heap Data structures are stored in the array.

$\implies $ Delete procedure for Min-Heap Data Structure (If you already know the value and position of the node):

  1. Replace that node with the last element of that tree.
  2. Apply Heapify property on that node.

For Example, Let If I want to delete $1$, then I will replace that with $27$. and apply heapify on that node. Or if i want to delete $5$ then also I will replace that with $27$, and apply heapify on that node.

Time Complexity: In this case, time complexity will not be more than $O(\log n)$.

$\implies $ Delete procedure for Min-Heap Data Structure (If you know the value but not position) :

  1. Find the position of the number by sequential search. (In the worst case it will take $O(n)$ time).
  2. Replace that node with the last element of that tree.
  3. Apply heapify property at that node. 

Time Complexity: Wort time complexity of this algorithm will be $\mathbf{O(n + \log n)}$ i.e. $\mathbf{O(n)}$.

Note: This is a standard problem of Minimum element deletion from the Min-heap tree. The minimum element always resides at top (Root node). We just replace that value with the last element of the tree and apply heapify at the root node. The time complexity of that algorithm is $\mathbf{O(\log n)}$. 

Here I have written the second method only to show that if we have to delete any of the nodes, and we just know the value but not the position. Since in question it is mentioned that Arbitrary node

edited by
by

4 Comments

edited by
@Anil

For 7 , 27 will replace 7
0
0
if u replace 5 by 17 then the tree will not be a heap bcz as a heap property it should be almost complete binary tree .   plz clear it ...
2
2

  is arbitary means here any node and we dont know the position?

0
0
4 votes
4 votes
Deleting an element from the min-heap, $O(\log n),$ but for searching in Heap we need $O(N).$

So, time complexity of the sequential search $+$ Delete $\implies O(N) + O(\log N) = O(N).$