Open In App

Introduction to Binary Tree

Last Updated : 02 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Binary Tree is a non-linear and hierarchical data structure where each node has at most two children 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.

Introduction-to-Binary-Tree
Introduction to Binary Tree

Representation of Binary Tree

Each node in a Binary Tree has three parts:

  • Data
  • Pointer to the left child
  • Pointer to the right child
Binary-Tree-Representation
Binary Tree Representation

Create/Declare a Node of a Binary Tree

Syntax to declare a Node of Binary Tree in different languages:

C++
// Use any below method to implement Nodes of binary tree

// 1: Using struct
struct Node {
    int data;
    Node* left, * right;

    Node(int key) {
        data = key;
        left = nullptr;
        right = nullptr;
    }
};

// 2: Using class
class Node {
public:
    int data;
    Node* left, * right;

    Node(int key) {
        data = key;
        left = nullptr;
        right = nullptr;
    }
};
C
// Structure of each node of the tree. 
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// Note : Unlike other languages, C does not support 
// Object Oriented Programming. So we need to write 
// a separat method for create and instance of tree node
struct Node* newNode(int item) {
    struct Node* temp = 
       (struct Node*)malloc(sizeof(struct Node));
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}
Java
// 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;
    }
}
Python
# 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
C#
// 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;
    }
}
JavaScript
/* Class containing left and right child 
  of current node and data*/

class Node
{
    constructor(item)
    {
        this.data = item;
        this.left = this.right = null;
    }
}

Example for Creating a Binary Tree

Here’s an example of creating a Binary Tree with four nodes (2, 3, 4, 5)

Binary-Tree-with-three-nodes
Creating a Binary Tree having three nodes
C++
#include <iostream>
using namespace std;

struct Node{
    int data;
    Node *left, *right;
    Node(int d){
        data = d;
        left = nullptr;
        right = nullptr;
    }
};

int main(){
    // Initilize and allocate memory for tree nodes
    Node* firstNode = new Node(2);
    Node* secondNode = new Node(3);
    Node* thirdNode = new Node(4);
    Node* fourthNode = new Node(5);

    // Connect binary tree nodes
    firstNode->left = secondNode;
    firstNode->right = thirdNode;
    secondNode->left = fourthNode;
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *left;
    struct Node *right;
};

struct Node* createNode(int d) {
    struct Node* newNode =
      (struct Node*)malloc(sizeof(struct Node));
    newNode->data = d;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

int main() {
    // Initialize and allocate memory for tree nodes
    struct Node* firstNode = createNode(2);
    struct Node* secondNode = createNode(3);
    struct Node* thirdNode = createNode(4);
    struct Node* fourthNode = createNode(5);

    // Connect binary tree nodes
    firstNode->left = secondNode;
    firstNode->right = thirdNode;
    secondNode->left = fourthNode;

    return 0;
}
Java
class Node {
    int data;
    Node left, right;
    Node(int d) {
        data = d;
        left = null;
        right = null;
    }
}

class GfG {
    public static void main(String[] args) {
        // Initialize and allocate memory for tree nodes
        Node firstNode = new Node(2);
        Node secondNode = new Node(3);
        Node thirdNode = new Node(4);
        Node fourthNode = new Node(5);

        // Connect binary tree nodes
        firstNode.left = secondNode;
        firstNode.right = thirdNode;
        secondNode.left = fourthNode;

    }
}
Python
class Node:
    def __init__(self, d):
        self.data = d
        self.left = None
        self.right = None

# Initialize and allocate memory for tree nodes
firstNode = Node(2)
secondNode = Node(3)
thirdNode = Node(4)
fourthNode = Node(5)

# Connect binary tree nodes
firstNode.left = secondNode
firstNode.right = thirdNode
secondNode.left = fourthNode
C#
using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int d) {
        this.data = d;
        left = null;
        right = null;
    }
}

class GfG {
    static void Main() {
        // Initialize and allocate memory for tree nodes
        Node firstNode = new Node(2);
        Node secondNode = new Node(3);
        Node thirdNode = new Node(4);
        Node fourthNode = new Node(5);

        // Connect binary tree nodes
        firstNode.left = secondNode;
        firstNode.right = thirdNode;
        secondNode.left = fourthNode;
    }
}
JavaScript
class Node {
    constructor(d) {
        this.data = d;
        this.left = null;
        this.right = null;
    }
}

// Initialize and allocate memory for tree nodes
let firstNode = new Node(2);
let secondNode = new Node(3);
let thirdNode = new Node(4);
let fourthNode = new Node(5);

// Connect binary tree nodes
firstNode.left = secondNode;
firstNode.right = thirdNode;
secondNode.left = fourthNode;

In the above code, we have created four tree nodes firstNode, secondNode, thirdNode and fourthNode having values 2, 3, 4 and 5 respectively.

  • After creating three nodes, we have connected these node to form the tree structure like mentioned in above image.
  • Connect the secondNode to the left of firstNode by firstNode->left = secondNode
  • Connect the thirdNode to the right of firstNode by firstNode->right = thirdNode
  • Connect the fourthNode to the left of secondNode by secondNode->left = fourthNode

Terminologies in Binary Tree

  • Nodes: The fundamental part of a binary tree, where each node contains data and link to two child nodes.
  • Root: The topmost node in a tree is known as the root node. It has no parent and serves as the starting point for all nodes in the tree.
  • Parent Node: A node that has one or more child nodes. In a binary tree, each node can have at most two children.
  • Child Node: A node that is a descendant of another node (its parent).
  • Leaf Node: A node that does not have any children or both children are null.
  • Internal Node: A node that has at least one child. This includes all nodes except the leaf nodes.
  • Depth of a Node: The number of edges from a specific node to the root node. The depth of the root node is zero.
  • Height of a Binary Tree: The number of nodes from the deepest leaf node to the root node.

The diagram below shows all these terms in a binary tree.

Terminologies-in-Binary-Tree-in-Data-Structure_1
Terminologies in Binary Tree in Data Structure

Properties of Binary Tree

  • The maximum number of nodes at level L of a binary tree is 2L
  • The maximum number of nodes in a binary tree of height H is 2H – 1
  • Total number of leaf nodes in a binary tree = total number of nodes with 2 children + 1
  • In a Binary Tree with N nodes, the minimum possible height or the minimum number of levels is Log2(N+1)
  • A Binary Tree with L leaves has at least | Log2L |+ 1 levels

Please refer Properties of Binary Tree for more details.

Operations On Binary Tree

Following is a list of common operations that can be performed on a binary tree:

1. Traversal

Traversal in Binary Tree involves visiting all the nodes of the binary tree. Tree Traversal algorithms can be classified broadly into two categories, DFS and BFS:

Depth-First Search (DFS) algorithms: DFS explores as far down a branch as possible before backtracking. It is implemented using recursion. The main traversal methods in DFS for binary trees are:

Breadth-First Search (BFS) algorithms: BFS explores all nodes at the present depth before moving on to nodes at the next depth level. It is typically implemented using a queue. BFS in a binary tree is commonly referred to as Level Order Traversal.

3. Search

Searching for a value in a binary tree means looking through the tree to find a node that has that value. Since binary trees do not have a specific order like binary search trees, we typically use any traversal method to search. Please refer Search a node in Binary Tree for details.

4. Insertion and Deletion

We must learn Level Order Traversal as a prerequisite for these operations. Please refer Insert in a Binary Tree and Delete from a Binary Tree for details.

Auxiliary Operations On Binary Tree

Complexity Analysis of Binary Tree Operations

Here’s the complexity analysis for specific binary tree operations:

OperationTime ComplexityAuxiliary Space
In-Order TraversalO(n)O(n)
Pre-Order TraversalO(n)O(n)
Post-Order TraversalO(n)O(n)
Searching (Unbalanced)O(n)O(n)

Note: We can use Morris Traversal to traverse all the nodes of the binary tree in O(n) time complexity but with O(1) auxiliary space.

Advantages of Binary Tree

  • Efficient Search: Binary Search Trees (a variation of Binary Tree) are efficient when searching for a specific element, as each node has at most two child nodes when compared to linked list and arrays
  • Memory Efficient: Binary trees require lesser memory as compared to other tree data structures, therefore memory-efficient.
  • Binary trees are relatively easy to implement and understand as each node has at most two children, left child and right child.

Disadvantages of Binary Tree

  • Limited structure: Binary trees are limited to two child nodes per node, which can limit their usefulness in certain applications. For example, if a tree requires more than two child nodes per node, a different tree structure may be more suitable.
  • Unbalanced trees: Unbalanced binary trees, where one subtree is significantly larger than the other, can lead to inefficient search operations. This can occur if the tree is not properly balanced or if data is inserted in a non-random order.
  • Space inefficiency: Binary trees can be space inefficient when compared to other data structures like arrays and linked list. This is because each node requires two child references or pointers, which can be a significant amount of memory overhead for large trees.
  • Slow performance in worst-case scenarios: In the worst-case scenario, a binary tree can become degenerate or skewed, meaning that each node has only one child. In this case, search operations in Binary Search Tree (a variation of Binary Tree) can degrade to O(n) time complexity, where n is the number of nodes in the tree.

Applications of Binary Tree

  • Binary Tree can be used to represent hierarchical data.
  • Huffman Coding trees are used in data compression algorithms.
  • Priority Queue is another application of binary tree that is used for searching maximum or minimum in O(1) time complexity.
  • Useful for indexing segmented at the database is useful in storing cache in the system,
  • Binary trees can be used to implement decision trees, a type of machine learning algorithm used for classification and regression analysis.

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.


Introduction to Binary Trees
Article Tags :
Practice Tags :

Similar Reads