VOOZH about

URL: https://www.geeksforgeeks.org/dsa/deletion-binary-tree/

⇱ Deletion in a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Deletion in a Binary Tree

Last Updated : 22 Oct, 2024

Given a binary tree, the task is to delete a given node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with the last element.

Examples :

Input : key = 10

πŸ‘ deletion-in-a-binary-tree

Output:    

πŸ‘ deletion-in-a-binary-tree-3


Explanation: As the bottom & rightmost node in the above binary tree is 30 , replace the key node ie. 10 with 30 and remove the bottom & rightmost node.

Input : key = 20

πŸ‘ deletion-in-a-binary-tree-2

Output:  

πŸ‘ deletion-in-a-binary-tree-4
Explanation: As the bottom & rightmost node in the above binary tree is 40, replace the key node ie. 20 with 40 and remove the bottom & rightmost node.

Approach:

The idea is to traverse the tree in level order manner. To perform the Deletion in a Binary Tree follow below:

  • Starting at the root, find the deepest and rightmost node in the binary tree and the node which we want to delete
  • Replace the deepest rightmost node’s data with the node to be deleted. 
  • Then delete the deepest rightmost node.

Below is the illustration of above approach:

πŸ‘ deletion-in-a-binary-tree-5


Below is the implementation of the above approach: 


Output
7 8 12 10 15 9 

Time complexity: O(n), where n is number of nodes.
Auxiliary Space: O(n)

Note: We can also replace the node's data that is to be deleted with any node whose left and right child points to NULL but we only use deepest node in order to maintain the Balance of a binary tree.

Comment
Article Tags: