Skip to main content

Posts

Showing posts with the label binary tree deletion

Binary tree deletion - non-recursive

In the previous post we have seen how to delete a node of a binary search tree using recursion. Today we will see how to delete a node of BST using a non-recursive function. Let us revisit the 3 scenarios here Deleting a node with no children just link the parent to NULL Deleting a node with one child link the parent to  non-null child of node to be deleted Deleting a node with both children select the successor of node to be deleted copy successor's value into this node delete the successor In order to start, we need a function to search for a node in binary search tree. Did you know that searching in  a BST is very fast, and is of the order O(logn). To search Start with root Repeat until value is found or node is NULL If the search value is greater than node branch to right If the search value is lesser than node branch to left.  Here is the function NODEPTR find_node (NODEPTR root,NODEPTR * parent, int delval) { NODEPTR nd = root; NODEPTR pa = root; if (ro...

Binary tree deletion

Do not get all scared and worried. It is not rocket science (or as I would like to call it - it is not regex). Remember deleting a node from linked list. When you deleted a node, you did the following 2 steps Free the memory of the node Link the previous node of the deleted node to the next node You will have to do these things in binary tree too. But the difficulty here is do you link the previous node - or parent node in tree terminology, to the left child of deleted node? Or to the right child? You can not link both children, as the parent already may have one child node. So before we solve this, let us categorize the deletion with the help of a diagram. Consider the cases The node to be deleted is a leaf node. That is, it does not have left or right child. In this case, link the parent to NULL in place of deleted node.  If you want to delete 13 - which is a leaf node, you set 14->left to NULL and free memory of node 13. If you want to delete 7 - which is also a leaf node and...