Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Memory representation of Binomial Heap
Next article icon

Binary Tree Representation

Last Updated : 07 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Binary tree is a tree data structure (non-linear) 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 can be represented in multiple ways, each with its own advantages, depending on the use case. Let's explore the two common methods: linked node representation and array implementation.

Representation of Binary Trees

There are two primary ways to represent binary trees:

  1. Linked Node Representation
  2. Array Representation

1. Linked Node Representation

This is the simplest way to represent a binary tree. Each node contains data and pointers to its left and right children.
This representation is mostly used to represent binary tree with multiple advantages. The most common advantages are given below.

Binary-Tree-Representation

Advantages:

  • It can easily grow or shrink as needed, so it uses only the memory it needs.
  • Adding or removing nodes is straightforward and requires only pointer adjustments.
  • Only uses memory for the nodes that exist, making it efficient for sparse trees.

Disadvantages:

  • Needs extra memory for pointers.
  • Finding a node can take longer because you have to start from the root and follow pointers.

Create/Declare a Node of a Binary Tree:

Syntax to declare a node of "linked list representation 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 val) {         data = val;         left = nullptr;         right = nullptr;     } };  // 2: Using class class Node { public:     int data;     Node* left, * right;      Node(int val) {         data = val;         left = nullptr;         right = nullptr;     } }; 
C
// Node structure of each node of the binary 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* createNode(int val) {     struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));     newNode->data = val;     newNode->left = NULL;     newNode->right = NULL;     return newNode; } 
Java
// Node structure of each node of the binary tree.  class Node {     int data;     Node left, right;      Node(int val) {         data = val;         left = null;         right = null;     } } 
Python
# Node structure of each node of the binary tree.  class Node:     def __init__(self, val):         self.data = val         self.left = None         self.right = None 
C#
// Node structure of each node of the binary tree.  class Node {     public int data;     public Node left, right;      public Node(int val) {         data = val;         left = null;         right = null;     } } 
JavaScript
// Node structure of each node of the binary tree.  class Node {     constructor(val) {         this.data = val;         this.left = null;         this.right = null;     } } 

For more detailed information about how it works, please check out our article "Introduction to Binary Tree".

2. Array Representation

Array Representation is another way to represent binary trees, especially useful when the tree is complete (all levels are fully filled except possibly the last, which is filled from left to right). In this method:

  • The tree is stored in an array.
  • For any node at index i:
    • Left Child: Located at 2 * i + 1
    • Right Child: Located at 2 * i + 2
  • Root Node: Stored at index 0
Array-Representation-of-Binary-Tree

Advantages:

  • Easy to navigate parent and child nodes using index calculations, which is fast
  • Easier to implement, especially for complete binary trees.

Disadvantages:

  • You have to set a size in advance, which can lead to wasted space.
  • If the tree is not complete binary tree then then many slots in the array might be empty, this will result in wasting memory
  • Not as flexible as linked representations for dynamic trees.

For more detailed information about how it works, please check out our article "Binary Tree (Array implementation)".

Comparison of Linked list vs Array Representation of Binary Tree

FeatureLinked Node RepresentationArray Representation
Memory UsageUses extra memory for pointersEfficient for complete trees
Ease of ImplementationSimple and intuitiveSimple but limited to complete trees
Dynamic SizeEasily grows and shrinksNot flexible for dynamic sizes
Access TimeSlower access for specific nodesFast access using indices
Suitable ForAny binary tree structureComplete binary tree



Next Article
Memory representation of Binomial Heap

H

harendrakumar123
Improve
Article Tags :
  • Tree
  • DSA
  • Binary Tree
Practice Tags :
  • Tree

Similar Reads

  • Array Representation Of Binary Heap
    A Binary Heap is a Complete Binary Tree. A binary heap is typically represented as array. The representation is done as: The root element will be at Arr[0]. Below table shows indexes of other nodes for the ith node, i.e., Arr[i]: Arr[(i-1)/2] Returns the parent node Arr[(2*i)+1] Returns the left chi
    1 min read
  • Memory representation of Binomial Heap
    Prerequisites: Binomial Heap Binomial trees are multi-way trees typically stored in the left-child, right-sibling representation, and each node stores its degree. Binomial heaps are collection of binomial trees stored in ascending order of size. The root list in the heap is a linked list of roots of
    2 min read
  • Binary representation of a given number
    Given an integer n, the task is to print the binary representation of the number. Note: The given number will be maximum of 32 bits, so append 0's to the left if the result string is smaller than 30 length. Examples: Input: n = 2Output: 00000000000000000000000000000010 Input: n = 0Output: 0000000000
    6 min read
  • Binary representation of previous number
    Given a binary input that represents binary representation of positive number n, find binary representation of n-1. It may be assumed that input binary number is greater than 0.The binary input may or may not fit even in unsigned long long int. Examples: Input : 10110Output : 10101Here n = (22)10 =
    6 min read
  • XOR counts of 0s and 1s in binary representation
    Given a number, the task is to find XOR of count of 0s and count of 1s in binary representation of a given number. Examples: Input : 5 Output : 3 Binary representation : 101 Count of 0s = 1, Count of 1s = 2 1 XOR 2 = 3. Input : 7 Output : 3 Binary representation : 111 Count of 0s = 0 Count of 1s = 3
    4 min read
  • Implementation of compressed 2D Binary Indexed tree
    A compressed 2D Binary Indexed Tree (BIT) is a data structure that is used to efficiently store and query two-dimensional arrays, particularly when the values in the array are frequently updated. The compressed 2D Binary Indexed Tree (BIT) is a data structure used for fast querying and updating valu
    15+ min read
  • Succinct Encoding of Binary Tree
    A succinct encoding of Binary Tree takes close to the minimum possible space. The number of structurally different binary trees on n nodes is n'th Catalan number. For large n, this is about 4n; thus we need at least about log2 4n = 2n bits to encode it. A succinct binary tree therefore would occupy
    10 min read
  • What is Binary Tree?
    A binary tree is a type of tree data structure in which each node can have at most two child nodes, known as the left child and the right child. Each node of the tree consists of - data and pointers to the left and the right child. Properties of a Binary Tree: The following are some of the important
    3 min read
  • Binary Tree Data Structure
    A Binary Tree Data Structure is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. It is commonly used in computer science for efficient storage and retrieval of data, with various operations such as insertion, deletion, and
    3 min read
  • What is Binary String?
    A binary string is a string that only has two characters, usually the numbers 0 and 1, and it represents a series of binary digits. Binary String Variables:In computer programming, binary string variables are used to store binary data, which is data that is represented in a binary (base-2) format, r
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences