Introduction to Binary Tree
Last Updated :
02 Aug, 2025
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 TreeRepresentation 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 RepresentationCreate/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)
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 StructureProperties 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:
Operation | Time Complexity | Auxiliary Space |
---|
In-Order Traversal | O(n) | O(n) |
Pre-Order Traversal | O(n) | O(n) |
Post-Order Traversal | O(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.
Related Articles:
Introduction to Binary Trees
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem