BCA / B.Tech 7 min read

Tree Algorithms

Tree Algorithms in Data Structures:


1. Inserting a Node (Insertion in Tree):

The process of adding a new node to a tree is called insertion. This operation can be performed differently in a Binary Search Tree and other tree structures.
Insertion Algorithm (in Binary Search Tree):
  • Start from the root node.
  • If the new data is smaller than the root, go to the left subtree. If the left subtree is empty, insert the new node there.
  • If the new data is larger than the root, go to the right subtree. If the right subtree is empty, insert the new node there.
  • Repeat this process until the correct spot is found.

2. Deleting a Node (Deletion in Tree):

Removing a node from a tree is a complex operation, as it can be divided into several cases:
  • If the node is a leaf, it can be directly removed.
  • If the node has only one child, connect that child to the parent.
  • If the node has two children, replace the node with its inorder successor or predecessor, and then delete that node.

3. Searching in a Tree:

This is the process of finding a given value in a tree. In a Binary Search Tree, the search operation can be completed in logarithmic time because the data is already ordered.
Search Algorithm (in Binary Search Tree): `Function Search(Node root, int key)` recursively searches the left or right subtree based on whether the key is smaller or larger than the current node's data.

4. Tree Traversal:

The process of visiting all the nodes of a tree in order. The main types are:
  • Inorder Traversal: Left subtree, Root, then Right subtree.
  • Preorder Traversal: Root, Left subtree, then Right subtree.
  • Postorder Traversal: Left subtree, Right subtree, then Root.

5. Height Calculation (Height of Tree):

The height of a tree represents the longest path from the root to a leaf node.
Height Algorithm: `Function Height(Node root)` recursively calculates the height of the left and right subtrees and returns the maximum of the two plus one.