Operation on Binary Tree :
Print this page
 

Insertion

   

The way to insert a new node in the tree, its value is first compared with the value of the root. If its value is less than the root's, it is then compared with the value of the root's left child. If its value is greater, it is compared with the root's right child. This process continues, until the new node is compared with a leaf node, and then it is added as this node's right or left child, depending on its value.

Another way is examine the root and recursively insert the new node to the left subtree if the new value is less than or equal to the root, or the right subtree if the new value is greater than the root.

 

Deletion

There are several cases to be considered:

  • Deleting a leaf: If the key to be deleted has an empty left or right subtree, Deleting the key is easy, we can simply remove it from the tree.
  • Deleting a node with one child: Delete the key and fill up this place with its child.
  • Deleting a node with two children: Suppose the key to be deleted is called K . We replace the key K with either its in-order successor (the left-most child of the right subtree) or the in-order predecessor (the right-most child of the left subtree). we find either the in-order successor or predecessor, swap it with K, and then delete it. Since either of these nodes must have less than two children (otherwise it cannot be the in-order successor or predecessor), it can be deleted using the previous two cases.
 

Sort

A binary tree can be used to implement a simple but inefficient sorting algorithm. We insert all the values we wish to sort into a new ordered data structure.

Prev
End