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:
Create Binary Tree with Nodes as Cumulative sum of children
Next article icon

Basic Operations on Binary Tree with Implementations

Last Updated : 24 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The tree is a hierarchical Data Structure. A binary tree is a tree that has at most two children. The node which is on the left of the Binary Tree is called “Left-Child” and the node which is on the right is called “Right-Child”. Also, the smaller tree or the subtree in the left of the root node is called the “Left sub-tree” and that on the right is called the “Right sub-tree”.

3

Binary Tree

Table of Content

  • Creation of Binary Tree
  • Traversal in a Binary Tree
  • The maximum element of the Binary Tree
  • Search for an element
  • Height of the tree
  • Deepest node of the tree 
  • Left view of the tree
  • Right view of the tree
  • Top view of the tree
  • Bottom view of the tree
  • The mirror image of the tree
  • Serialize a tree

Below are the various operations that can be performed on a Binary Tree

1. Creation of Binary Tree

A binary tree is a hierarchical data structure where each node has at most two children, referred to as the left child and the right child. The binary tree consists of a root node, where the tree starts, and subtrees rooted at each node. Nodes in a binary tree are linked via edges, and each node contains a data element.

Key Characteristics:

  • Root Node: The topmost node of the tree. It doesn’t have a parent.
  • Parent and Child Nodes: In a binary tree, each node (except the root) has exactly one parent, and a node can have at most two children (left and right).
  • Leaf Node: A node that has no children.
  • Subtree: A tree that is a part of a larger tree, starting from any node.

Binary Tree Structure: A binary tree is typically represented by nodes, where each node consists of:

  • Data: Stores the actual data of the node.
  • Left Pointer: Points to the left child.
  • Right Pointer: Points to the right child.

To read more about Creation of Binary Tree Refer, Binary Tree Representation

2. Traversal in a Binary Tree

Traversal in a binary tree refers to the process of visiting each node in the tree in a specific order. There are several methods of traversing a binary tree, each serving different purposes depending on the task. The three most commonly used traversal methods are In-order Traversal, Pre-order Traversal, and Post-order Traversal. Additionally, Level-order Traversal is often used for breadth-first traversal.

Types of Binary Tree Traversal

In-order Traversal: In in-order traversal, you first visit the left subtree, then the root node, and finally the right subtree. For a binary search tree, this traversal visits nodes in ascending order.

To read more about in-order traversal Refer, Inorder Traversal of Binary Tree

Pre-order Traversal: In pre-order traversal, you first visit the root node, then the left subtree, and then the right subtree. This method is often used for tasks such as creating a copy of the tree or storing a tree structure.

To read more about pre-order traversal Refer, Preorder Traversal of Binary Tree

Post-order Traversal: In post-order traversal, you first visit the left subtree, then the right subtree, and finally the root node. This is useful for applications where you need to process the children nodes before the parent node (e.g., deleting a tree).

To read more about post-order traversal Refer, Postorder Traversal of Binary Tree

Level-order Traversal: In level-order traversal, nodes are visited level by level, from top to bottom and left to right. This is often implemented using a queue to handle nodes level by level.

To read more about level order traversal Refer, Level Order Traversal (Breadth First Search or BFS) of Binary Tree

Reverse Level Order Traversal: Reverse Level Order Traversal is a traversal method for binary trees where you visit all the nodes of the tree level by level, but instead of visiting them from top to bottom, you visit them from bottom to top. Within each level, nodes are visited from left to right.

To read more about reverse level order traversal Refer, Reverse Level Order Traversal

3. The maximum element of the Binary Tree

To find the maximum element in a binary tree, we need to traverse all the nodes in the tree and keep track of the largest value encountered. This is generally done using a traversal method such as in-order, pre-order, post-order, or level-order, depending on the needs of the application.

The basic idea is to:

  • Start at the root node.
  • Traverse each node.
  • Compare the current node’s value with the current maximum value.
  • Update the maximum value if the current node’s value is greater.

Approach:

  1. Recursive Method: This is a simple and efficient way to find the maximum element. You can traverse the tree recursively using a depth-first traversal method (like in-order or pre-order).
  2. Iterative Method: This method uses a breadth-first traversal (like level-order) with a queue, which also ensures that each node is visited.

To read more about maximum element of the binary tree Refer, Find maximum (or minimum) in Binary Tree

4. Search for an element

To search for an element in a binary tree, we need to traverse the tree and check each node to see if its value matches the target element. Depending on the tree structure (binary search tree or a general binary tree), the method of traversal can differ, but the basic idea remains the same.

Approach:

  1. Recursive Search:
    • Start at the root node.
    • If the node’s value matches the target, return true (found).
    • Recursively search in the left and right subtrees if the node’s value does not match.
    • If the target value is not found in either subtree, return false.
  2. Iterative Search (using level-order traversal):
    • A queue or stack is used to store nodes for level-order or depth-first traversal.
    • Traverse the tree while comparing each node with the target value.

To read more about search for an element Refer, Search a node in Binary Tree

5. Height of the tree

The height of a binary tree is the number of edges on the longest path from the root to any leaf node. In simpler terms, it represents the maximum depth of the tree.

  • The height of an empty tree is considered as -1.
  • The height of a tree with just one node (root) is 0.
  • The height of a non-empty tree is defined as 1 + max(height of left subtree, height of right subtree).

To read more about Height of the tree Refer, Maximum Depth of Binary Tree

6. Deepest node of the tree 

The deepest node in a binary tree is the node that is the furthest from the root. It is typically the node that appears at the last level of the tree, and if there are multiple nodes at that level, the deepest node is the one that is farthest to the right (in the case of a level-order traversal).

In simple terms, it is the node at the maximum depth or height of the tree. To find the deepest node, we can perform a level-order traversal (breadth-first search) using a queue, and the last node we visit will be the deepest node.

Steps to Find the Deepest Node:

  • Perform Level-order Traversal: Use a queue to visit each node level by level.
  • Track the Last Node Visited: The last node visited in the level-order traversal will be the deepest node.
  • Return the Deepest Node: Once the traversal is complete, return the last node that was visited.

To read more about the Deepest Node in a Binary Tree Refer, Find the Deepest Node in a Binary Tree

7. Left view of the tree

The left view of a binary tree refers to the set of nodes visible when the tree is viewed from the left side. In other words, it consists of the first node visible at each level when the tree is viewed from the left.

  • For each level, you only see the leftmost node.
  • To find the left view, a level-order traversal is often used, but we only need to capture the first node encountered at each level.

Steps to Find the Left View

  • Perform a level-order traversal of the tree using a queue.
  • For each level, print the first node encountered at that level.
  • Ensure that only the first node at each level is added to the output (ignoring the others at the same level).

To read more about Left view of the tree Refer, Left View of a Binary Tree

8. Right view of the tree

The right view of a binary tree is the set of nodes visible when the tree is viewed from the right side. In simpler terms, it consists of the rightmost node at each level of the tree.

  • For each level of the tree, only the rightmost node is visible when viewed from the right side.
  • To obtain the right view, we can perform a level-order traversal (breadth-first search) and capture the last node visited at each level.

Steps to Find the Right View

  1. Perform a level-order traversal using a queue to visit each node level by level.
  2. For each level, only print the last node encountered at that level.
  3. The last node at each level will be the rightmost node and will be included in the right view.

To read more about Right view of the tree Refer, Print Right View of a Binary Tree

9. Top view of the tree

The top view of a binary tree is the set of nodes visible when the tree is viewed from the top. In other words, the top view consists of the first node encountered at each horizontal distance from the root.

  • Horizontal Distance: Each node in the tree has a horizontal distance relative to the root node. The root node has a horizontal distance of 0. Nodes to the left of the root have negative horizontal distances, and nodes to the right have positive horizontal distances.
  • For each horizontal distance, only the first node that appears in the level-order traversal (topmost node) is visible.

Steps to Find the Top View

  1. Perform a level-order traversal of the tree, but during this traversal, track the horizontal distance of each node.
  2. For each horizontal distance, print the first node encountered at that distance.
  3. Ensure that each horizontal distance is represented only once in the top view.

To read more about Top view of the tree Refer, Print Nodes in Top View of Binary Tree

10. Bottom view of the tree

The bottom view of a binary tree is the set of nodes visible when the tree is viewed from the bottom. This view consists of the last node encountered at each horizontal distance from the root node when traversing the tree from top to bottom.

  • Horizontal Distance: Similar to the top view, the root node has a horizontal distance of 0, nodes to the left have negative distances, and nodes to the right have positive distances.
  • For each horizontal distance, the last node encountered at that horizontal distance is visible in the bottom view.

Steps to Find the Bottom View

  1. Perform a level-order traversal of the tree while keeping track of the horizontal distance of each node.
  2. For each horizontal distance, update the node if it’s the last node encountered at that distance.
  3. After the traversal, print the node corresponding to each horizontal distance in increasing order.

To read more about Bottom view of the tree Refer, Bottom View of a Binary Tree

11. The mirror image of the tree

The mirror image of a binary tree is a reflection of the tree along its vertical axis. In the mirror image, the left and right subtrees of every node are swapped.

Steps to Create a Mirror Image of a Binary Tree

  1. Swap the Left and Right Subtrees: For every node in the tree, swap its left and right children.
  2. Recursive Approach: Perform this swapping recursively for each node, starting from the root.
  3. After the swapping, the tree will be its mirror image

To read more about mirror image of the tree Refer, Invert Binary Tree – Change to Mirror Tree

12. Serialize a tree

Serialization is the process of converting a binary tree into a linear form (such as a string or array) so that it can be easily stored or transmitted and later reconstructed. This is essential for saving the state of a tree or sending it over a network.

Deserialization is the process of reconstructing the binary tree from its serialized form.

Approach to Serialize a Binary Tree

  1. Pre-order Traversal: Serialize the tree using pre-order traversal (visit the node, then left subtree, then right subtree).
  2. Marking Null Nodes: Since binary trees may have null nodes, mark them with a special value (like "null") so they can be properly reconstructed later.
  3. Store Data in a String or Array: The tree is serialized into a string or array, where each node’s value is separated by a delimiter (such as a comma).

To read more about serialize tree Refer, Serialize and Deserialize a Binary Tree



Next Article
Create Binary Tree with Nodes as Cumulative sum of children
author
imsushant12
Improve
Article Tags :
  • DSA
  • Experiences
  • Internship
  • Recursion
  • Technical Scripter
  • Tree
  • Binary Tree
  • Inorder Traversal
  • PostOrder Traversal
  • Preorder Traversal
  • Technical Scripter 2020
  • tree-level-order
  • tree-traversal
Practice Tags :
  • Recursion
  • Tree

Similar Reads

  • Binary Tree (Array implementation)
    Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation o
    6 min read
  • B*-Trees implementation in C++
    B*-tree of order m is a search tree that is either empty or that satisfies three properties: The root node has minimum two and maximum 2 floor ((2m-2)/3) +1 children Other internal nodes have the minimum floor ((2m-1)/3) and maximum m children All external nodes are on the same level. The advantage
    10 min read
  • Replace node with depth in a binary tree
    Given a binary tree, replace each node with its depth value. For example, consider the following tree. Root is at depth 0, change its value to 0 and next level nodes are at depth 1 and so on. 3 0 / \ / \ 2 5 == >; 1 1 / \ / \ 1 4 2 2 The idea is to traverse tree starting from root. While traversi
    11 min read
  • Expression Trees Using Classes in C++ with Implementation
    Prerequisite: Expression Tree The expression tree is a binary tree in which each internal node corresponds to the operator and each leaf node corresponds to the operand so for example expression tree for 3 + ((5+9)*2) would be: In expression trees, leaf nodes are operands and non-leaf nodes are oper
    4 min read
  • Create Binary Tree with Nodes as Cumulative sum of children
    Given a root of a Binary Tree, the task is to update each of its nodes with the sum of all the nodes below it (from its left and right subtree), inclusive of the current Node. Example: Approach: The idea is to simply traverse through left and right subtree, and calculate sum of Left Subtree & Ri
    7 min read
  • Implement Binary Search Tree(BST) Iterator
    Binary Search Trees (BSTs) are data structures, in computer science. They are commonly used for searching, insertion and deletion operations. In situations it becomes necessary to traverse a BST in an order. For example an in order traversal visits nodes in ascending order based on their values. Thi
    6 min read
  • Print Levels of all nodes in a Binary Tree
    Given a Binary Tree and a key, write a function that prints levels of all keys in given binary tree. For example, consider the following tree. If the input key is 3, then your function should return 1. If the input key is 4, then your function should return 3. And for key which is not present in key
    7 min read
  • Check whether a given Binary Tree is Complete or not (Iterative Solution)
    Given a Binary Tree, the task is to check whether the given Binary Tree is a Complete Binary Tree or not.A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Examples: The following trees are examples
    12 min read
  • Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
    In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delet
    4 min read
  • Insert Operation in B-Tree
    In this post, we'll discuss the insert() operation in a B-Tree. A new key is always inserted into a leaf node. To insert a key k, we start from the root and traverse down the tree until we reach the appropriate leaf node. Once there, the key is added to the leaf. Unlike Binary Search Trees (BSTs), n
    15+ 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