Basic Operations on Binary Trees
Introductionβ
Binary trees are a versatile data structure that allows for efficient operations like searching, insertion, and deletion. In this post, weβll explore the core operations used to manipulate binary trees, along with traversal methods that are key to utilizing binary trees effectively.
Basic Operations on Binary Treesβ
1. Insertionβ
Inserting a new node into a binary tree involves placing the node in its correct position, maintaining the structure of the binary tree.
Example in C++:β
// Insert function
Node* insert(Node* root, int val) {
if (root == nullptr) {
return new Node(val); // Inserting at an empty spot
}
if (val < root->data) {
root->left = insert(root->left, val);//Traversing to left sub-tree
} else {
root->right = insert(root->right, val);//Traversing to right sub-tree
}
return root;
}
Inserting E at the right of B
A A
/ \ / \
B C ------> B C
/ / \ / \ / \
D F G D E F G
2. Deletionβ
In a binary tree, when deleting a node, the node to be deleted is replaced by the deepest node in the tree. This approach ensures that the tree remains complete. The deletion process involves the following steps: