Skip to main content

Posts

Showing posts from March, 2012

Function to add a node to binary search tree

Binary search tree (BST) is an ordered tree where each node has smaller values on the left sub tree and larger values on the right subtree. This is similar to binary search algorithm. And another useful fact is if you traverse the node in in-order method, the values of the tree will be in ascending order. Binary Search Tree with root as 50 Now as you can see from the diagram on the left child and their children of root (which in this case is 50), values are 40, 20 and 45. All are less than 50. On the other hand, on the right sub tree 50, the values are 60, 55 and 78 - larger than 50. And this rule follows for each and every node, not just root. Now if we have to  add a node - let us 43, where shall we add it, in such a way that the tree will still remain as BST. The new node must be a leaf node (i.e. the node with no child nodes) Let us traverse from root and find out where this new node fits. 43 is smaller than 50. Hence we must branch to left of 50. Now we get 40. 43 is

Deletion of a node from linked list given only that node

We have considered how to create and print the list and delete a node from a list. But often interviewers ask you a question, given a node of the list, how do you delete that node? The problem here is we do not know the head of the list. We just the know one node which we must delete. Well, the solution is much simpler than it appears. Suppose 12 is the node which should be deleted. As we can see from the diagram, we are deleting the next node of 99 by the usual method of linking n to next of next of 12. But the requirement was not to delete next node  but the node with 12 itself. So we will retain the data of that node (99) by copying it to previous node. And now the node with 99 is marked for deletion. Which can be easily deleted as follows. We are assuming that n is the node with 12 as value. n -> data = n -> next -> data; //copy the data n -> next = n -> next -> next; //link to next free( n -> next) ; //delete next of n