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.
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.
π 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.
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.