Open In App

Introduction to Binary Tree – Data Structure and Algorithm Tutorials

A binary tree is a tree data structure in which each node can have at most two children, which are referred to as the left child and the right child. 

The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. A binary tree can be visualized as a hierarchical structure with the root at the top and the leaves at the bottom.



Binary trees have many applications in computer science, including data storage and retrieval, expression evaluation, network routing, and game AI. They can also be used to implement various algorithms such as searching, sorting, and graph algorithms.

Representation of Binary Tree:

Each node in the tree contains the following:



Binary Tree

In C, we can represent a tree node using structures. In other languages, we can use classes as part of their OOP feature. Below is an example of a tree node with integer data.




// Structure of each node of the tree
 
struct node {
    int data;
    struct node* left;
    struct node* right;
};




// Use any below method to implement Nodes of tree
 
// Method 1: Using "struct" to make
// user-define data type
struct node {
    int data;
    struct node* left;
    struct node* right;
};
 
// Method 2: Using "class" to make
// user-define data type
class Node {
public:
    int data;
    Node* left;
    Node* right;
};




# A Python class that represents
# an individual node in a Binary Tree
 
class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key




// Class containing left and right child
// of current node and key value
class Node {
    int key;
    Node left, right;
 
    public Node(int item)
    {
        key = item;
        left = right = null;
    }
}




// Class containing left and right child
// of current node and key value
 
class Node {
    int key;
    Node left, right;
 
    public Node(int item)
    {
        key = item;
        left = right = null;
    }
}




<script>
/* Class containing left and right child of current
   node and key value*/
 
class Node
{
    constructor(item)
    {
        this.key = item;
        this.left = this.right = null;
    }
}
 
// This code is contributed by umadevi9616
</script>

Basic Operations On Binary Tree:

Auxiliary Operations On Binary Tree:

Applications of Binary Tree:

Binary Tree Traversals:

Tree Traversal algorithms can be classified broadly into two categories:

Tree Traversal using Depth-First Search (DFS) algorithm can be further classified into three categories:

Tree Traversal using Breadth-First Search (BFS) algorithm can be further classified into one category:

Let us traverse the following tree with all four traversal methods:

Binary Tree

Pre-order Traversal of the above tree: 1-2-4-5-3-6-7
In-order Traversal of the above tree: 4-2-5-1-6-3-7
Post-order Traversal of the above tree: 4-5-2-6-7-3-1
Level-order Traversal of the above tree: 1-2-3-4-5-6-7

Implementation of Binary Tree:

Let us create a simple tree with 4 nodes. The created tree would be as follows. 

Binary Tree

Below is the Implementation of the binary tree:




#include <stdio.h>
#include <stdlib.h>
 
struct node {
    int data;
    struct node* left;
    struct node* right;
};
 
// newNode() allocates a new node
// with the given data and NULL left
// and right pointers.
struct node* newNode(int data)
{
    // Allocate memory for new node
    struct node* node
        = (struct node*)malloc(sizeof(struct node));
 
    // Assign data to this node
    node->data = data;
 
    // Initialize left and
    // right children as NULL
    node->left = NULL;
    node->right = NULL;
    return (node);
}
 
int main()
{
    // Create root
    struct node* root = newNode(1);
 
    /* following is the tree after above statement
        1
       /  \
     NULL NULL
    */
    root->left = newNode(2);
    root->right = newNode(3);
 
    /* 2 and 3 become left and right children of 1
            1
           / \
          2   3
         / \ / \
    NULL NULL NULL NULL
    */
    root->left->left = newNode(4);
 
    /* 4 becomes left child of 2
         1
        / \
       2   3
      /  \ / \
     4 NULL NULL NULL
     /   \
    NULL NULL
    */
    getchar();
    return 0;
}




#include <bits/stdc++.h>
using namespace std;
 
class Node {
public:
    int data;
    Node* left;
    Node* right;
    // Val is the key or the value that
    // has to be added to the data part
    Node(int val)
    {
        data = val;
        // Left and right child for node
        // will be initialized to null
        left = NULL;
        right = NULL;
    }
};
 
int main()
{
    /*create root*/
    Node* root = new Node(1);
 
    /* following is the tree after above statement
    1
    / \
    NULL NULL
    */
    root->left = new Node(2);
    root->right = new Node(3);
 
    /* 2 and 3 become left and right children of 1
       1
      / \
     2   3
    / \ / \
    NULL NULL NULL NULL
    */
    root->left->left = new Node(4);
    /* 4 becomes left child of 2
         1
       /   \
      2     3
     / \    / \
    4 NULL NULL NULL
    /   \
    NULL NULL
    */
    return 0;
}




// Class containing left and right child
// of current node and key value
class Node {
 
    int key;
 
    Node left, right;
    public Node(int item)
    {
        key = item;
        left = right = null;
    }
}
 
// A Java program to introduce Binary Tree
class BinaryTree {
     
    // Root of Binary Tree
    Node root;
     
    // Constructors
    BinaryTree(int key) { root = new Node(key); }
    BinaryTree() { root = null; }
    public static void main(String[] args)
    {
        BinaryTree tree = new BinaryTree();
         
        // Create root
        tree.root = new Node(1);
        /* Following is the tree after above statement
           1
          / \
        null null
        */
 
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        /* 2 and 3 become left and right children of 1
              1
             / \
            2   3
           / \ / \
       null null null null */
        tree.root.left.left = new Node(4);
        /* 4 becomes left child of 2
               1
              / \
             2   3
            / \ / \
           4 null null null
          / \
        null null
        */
    }
}




# Python program to introduce Binary Tree
# A class that represents an individual node
# in a Binary Tree
 
 
class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key
 
 
# Driver code
if __name__ == '__main__':
    # Create root
    root = Node(1)
    ''' following is the tree after above statement
    1
    / \
    None None'''
    root.left = Node(2)
    root.right = Node(3)
 
    ''' 2 and 3 become left and right children of 1
       1
      /  \
     2    3
    / \  / \
   None None None None'''
 
    root.left.left = Node(4)
    '''4 becomes left child of 2
        1
       / \
      2   3
     / \ / \
    4 None None None
   / \
   None None'''




// A C# program to introduce Binary Tree
 
using System;
 
// Class containing left and right child
// of current node and key value
public class Node {
    public int key;
    public Node left, right;
    public Node(int item)
    {
        key = item;
        left = right = null;
    }
}
 
public class BinaryTree {
 
    // Root of Binary Tree
    Node root;
    // Constructors
    BinaryTree(int key) { root = new Node(key); }
 
    BinaryTree() { root = null; }
 
    // Driver Code
    public static void Main(String[] args)
 
    {
        BinaryTree tree = new BinaryTree();
        // Create root
        tree.root = new Node(1);
        /* Following is the tree after above statement
           1
          / \
        null null */
         
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        /* 2 and 3 become left and right children of 1
             1
            / \
           2   3
          / \ / \
    null null null null */
 
        tree.root.left.left = new Node(4);
        /* 4 becomes left child of 2
           1
          / \
         2   3
        / \ / \
     4 null null null
       / \
    null null
*/
    }
}
 
// This code is contributed by PrinciRaj1992




<script>
 
/* Class containing left and right child of current
 
node and key value*/
class Node {
 
constructor(val) {
this.key = val;
this.left = null;
this.right = null;
}
  
}
 
// A javascript program to introduce Binary Tree
// Root of Binary Tree
 
var root = null;
 
/*create root*/
 
root = new Node(1);
 
/* following is the tree after above statement
1
/ \
null null */
  
root.left = new Node(2);
 
root.right = new Node(3);
  
/* 2 and 3 become left and right children of 1
1
/ \
2 3
/ \ / \
null null null null */
  
root.left.left = new Node(4);
  
/* 4 becomes left child of 2
1
/ \
2 3
/ \ / \
4 null null null
/ \
null null
*/
</script>

Conclusion:

Tree is a hierarchical data structure. Main uses of trees include maintaining hierarchical data, providing moderate access and insert/delete operations. Binary trees are special cases of tree where every node has at most two children.

What else can you read?


Article Tags :