Skip to main content

Binary Tree 🌳

A Binary Tree is a non-linear data structure that has a mazimum of two children for each parent. The first node of the tree is called the root node and the other other nodes are associated with one parent node.

Binary Tree

Each node in a binary tree has a left and right reference, and a data/value field. The data field contains the value to be stored in the node while the left and right fields contain a reference to the left and right child nodes respectively.

Binary Tree

credit https://www.upgrad.com/blog/5-types-of-binary-tree/

Terminologies#

  1. Node - The termination point of a tree. Single element structure of a tree.

  2. Root - The first node of the tree.

  3. Parent - Each node of the tree except the root that has at least one child

  4. Leaf Node - Nodes without children

  5. Child - Sub-node of a parent node.

  6. Internal node - Inner nodes with at least one child

  7. Depth of tree - The number of edges from the tree's node to the root.

  8. Height of tree - Number of edges from the node to the deepest leaf.

Types of Binary Tree#

Binary Trees can be of the following types:

  1. Full Binary Tree βˆ’ The parent nodes have either zero or two children.

Full Binary Tree

credit https://www.upgrad.com/blog/5-types-of-binary-tree/

  1. Complete Binary Tree βˆ’ All the tree levels are filled completely with nodes except the lowest level of the tree. If he last node has one child, it should reside on the left.

Complete Binary Tree

credit https://www.upgrad.com/blog/5-types-of-binary-tree/

  1. Perfect Binary Tree βˆ’ All the parent nodes (internal nodes) have two children and every leaf node is at the same depth.

Perfect Binary Tree

credit https://www.upgrad.com/blog/5-types-of-binary-tree/

  1. Balanced Binary Tree - The left and right subtrees of every node differ in height by no more than 1.

Balanced Binary Tree

credit https://www.upgrad.com/blog/5-types-of-binary-tree/

  1. Degenerate Binary Tree - Every internal node has only a single child.

Degenerate Binary Tree

credit https://www.upgrad.com/blog/5-types-of-binary-tree/

Basic operations#

When we want to operate on data in a Binary Tree we can perfomr the following operations:

  1. Insertion βˆ’ Adding a node between other nodes or added after a leaf node.
  2. Deletion βˆ’ Delete a node from the tree.
  3. Trecersal βˆ’ Pre-order, in-order and post-order traversal visit each noe in a tree by recursively visiting each node on the left and right subtrees.
  4. Search βˆ’ Searches for node holding a a given pi

Advantages of Binary Trees#

  • An ideal way to store data in a hierachy
  • Reflects structural relationships that exist in given data set.
  • Faster to access elements than linked lists.
  • Searching takes O(logn) time instead of O(n).
  • Elements can be retrieved in sorted order.

Disadvantages of Binary Trees#

  • The memory is wasted as pointers require extra memory for storage.
  • Sequential storage may waste space.
  • It takes O(logn) time to modify the list (balanced trees take longer - this is for the baseline) and to retrieve elements with a known location.
  • There is no efficient traversal

Applications of Binary Trees#

  • Binary Search Tree - Used in many search applications that constantly show and hide data, such as data. For example, map and set objects in many libraries.

  • Binary Space Partition - Used in almost any 3D video game to determine which objects need to be rendered.

  • Binary Tries - Used in almost every high-bandwidth router to store router tables.

  • Syntax Tree - Constructed by compilers and (implicit) calculators to parse expressions.

  • Hash Trees - Used in P2P programs and special image signatures that require a hash to be validated, but the entire file is not available.

  • Heaps - Used to implement efficient priority queues and also used in heap sort.

  • Treap - Randomized data structure for wireless networks and - memory allocation.

  • T-Tree - Although most databases use a form of B-tree to store data on the drive, databases that store all (most) data often use T-trees.

  • Huffman Coding Tree (Chip Uni) - Used in compression algorithms, eg. For example, in .jpeg and .mp3.GGM Trees file formats - used in cryptographic applications to generate a tree with pseudo-random numbers.

Sample Code#

#include <stdlib.h>#include <iostream>
using namespace std;
struct node{    int data;    struct node *left;    struct node *right;};
// New node creationstruct node *newNode(int data){    struct node *node = (struct node *)malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;    node->right = NULL;    return (node);}
void addNode(struct node** root, int data){    if (*root == NULL)    {        *root = newNode(data);    }    else    {        if ((*root)->data > data)        {            if ((*root)->left != NULL)                addNode(&(*root)->left, data);            else                (*root)->left = newNode(data);        }        else        {            if ((*root)->right != NULL)                addNode(&(*root)->right, data);            else                (*root)->right =  newNode(data);        }    }}
void _printBinaryTree(struct node *node){    if (node != NULL)    {        _printBinaryTree(node->left);        cout << node->data << " is a value held in a node" << endl;        _printBinaryTree(node->right);    }}
void printBinaryTree(struct node *root){    if (root != NULL)        _printBinaryTree(root);    else        cout << "The Binary Tree is empty" << endl;}
// Traverse Preordervoid traversePreOrder(struct node *node) {    if (node != NULL)    {        cout << " " << node->data;        traversePreOrder(node->left);        traversePreOrder(node->right);    }}
// Traverse Inordervoid traverseInOrder(struct node *node) {    if (node != NULL)    {        traverseInOrder(node->left);        cout << " " << node->data;        traverseInOrder(node->right);    }}
// Traverse Postordervoid traversePostOrder(struct node *node) {    if (node != NULL) {        traversePostOrder(node->left);        traversePostOrder(node->right);        cout << " " << node->data;    }}


int main(){    struct node* root = NULL;
    addNode(&root, 5);    addNode(&root, 2);    addNode(&root, 8);    addNode(&root, 4);    addNode(&root, 1);    addNode(&root, 7);    addNode(&root, 12);    addNode(&root, 19);    addNode(&root, 33);    addNode(&root, 6);
    cout << "------- Start of Binary Tree -------\n" << endl;    printBinaryTree(root);    cout << "\n------- End of Binary Tree -------\n" << endl;
    cout << "\n------- Preorder traversal ---------" << endl;    traversePreOrder(root);    cout << "\n\n------- Inorder traversal ----------" << endl;    traverseInOrder(root);    cout << "\n\n------- Postorder traversal -------- " << endl;    traversePostOrder(root);    cout << "" << endl;
    return (0);}

Compilation#

Compilation for cpp

What's next?#

Anything unclear or buggy in this tutorial? Please report it!