Dsa Notes Topic Upto Tree
Dsa Notes Topic Upto Tree
According to the data types, the data structure is divided into two categories,
namely:
▪ Primitive Data Structures
▪ Non-Primitive Data Structures
➢ Primitive Data Structures:
This type of data structure stores the value of a particular data type. For example, an
integer data structure can store the value of only an integer. A primitive data
structure cannot be NULL.
❖ The following are the primitive data structures:
▪ Integer: It represents a whole number data type with no decimal places.
For example, int num = 30
▪ Float: It is a data type with decimal precision.
For example, float num = 2346.9875
▪ Character: It represents a single character.
For example, char name = “M”
▪ Boolean: It returns true or false values for a condition specified.
For example, boolean value = “true”
➢ Non-Primitive Data Structures:
These data structures are capable of storing values of more than one data type. The
size of the non-primitive data structure depends on the type of data it will store. For
example, a list (a non-primitive data structure) can store the values of various data
types. It can contain a NULL value.
➢ The following are some of the non-primitive data structures:
▪ List: A list is a linear type of data structure. This data structure holds an ordered list of
elements.
For example,
list_of_networks [“Airtel”, ”Jio”, “Idea”]
▪ Arrays: An array is also a linear data structure that stores a collection of data having
the same data type. It has a fixed size, which means it stores data in a contagious
memory location of the same data type (int, float, boolean, text, and others).
For example,
int[] numbers = {1, 2, 3, 4, 5}
▪ Queue: A Queue is a data structure that arranges items in a specific order and
follows the First-In-First-Out (FIFO) method for accessing elements. It is commonly
employed in building priority queuing systems and handling threads in multithreading
scenarios.
For example,
String[] names = {"Alice", "Charlie", "David", "Emily"};
▪ Stack: Based on the principle ‘last in, first out’ or LIFO, a stack is an abstract data type
that is composed of homogenous pieces. It is used for push and pop operations that
are applied on top of the stack. While the pop operation is responsible for removing
an element from the top spot, the push operation adds an element to the stack.
For example,
stack = [1,2,3,4,5]
▪ Tree: This is a non-linear and hierarchical data structure. A tree is a hierarchical
structure with nodes connected by edges, with the root being the top node and child
nodes below it.
For example,
tree = Tree(1, Tree(2, 2.1, 2.2), Tree(3, 3.1))
➢ Linear Data Structure: Data structure in which data elements are arranged
sequentially or linearly, where each element is attached to its previous and next
adjacent elements, is called a linear data structure.
Example: Array, Stack, Queue, Linked List, etc.
➢ Static Data Structure: Static data structure has a fixed memory size. It is easier to
access the elements in a static data structure.
Example: array.
➢ Dynamic Data Structure: In dynamic data structure, the size is not fixed. It can be
randomly updated during the runtime which may be considered efficient concerning
the memory (space) complexity of the code.
Example: Queue, Stack, etc.
➢ Non-Linear Data Structure: Data structures where data elements are not placed
sequentially or linearly are called non-linear data structures. In a non-linear data
structure, we can’t traverse all the elements in a single run only.
Examples: Trees and Graphs.
➢ Need Of Data structure :
1. Data structure modification is easy.
2. It requires less time.
3. Save storage memory space.
4. Data representation is easy.
5. Easy access to the large database.
➢ Advantages & Disadvantages of Data Structure:
➢ Advantages of Data Structure:
Data structures offer a wide range of benefits for creating and maintaining code in
programming languages. Some of these advantages are:
1) Efficient Storage
Data structures provide efficient storage by organizing the data effectively, which facilitates
quick retrieval and maintenance of the data in the system. The memory allocation takes
place according to the data types used in the data structure.
3) Develop Algorithms
Algorithms for data structures help organize and access information in a structured manner.
These algorithms take into account the format of the data as well as any actions that can be
performed on it. Their goal is to find the most efficient way to store and manipulate data
within the structure while also allowing for easy navigation. By utilizing these algorithms,
complex issues can be resolved with efficiency.
4) Reusability of Data
One of the fundamental advantages of data structure is that it offers data reusability. It
enables the creation of data in specific formats, which can then be stored in libraries,
allowing different clients to utilize and access the data as needed. Therefore, data can be
reused in multiple ways and purposes. This makes it easier to create efficient and dynamic
algorithms that can be used for different applications.
Name Expresses
LLONG_MIN The minimum value for an object of type long long int
ULLONG_MAX Maximum value for an object of type Unsigned long long int
The data type is the form of a variable to Data structure is a collection of different
which a value can be assigned. It defines kinds of data. That entire data can be
Data Type Data Structure
that the particular variable will assign the represented using an object and can be
values of the given data type only. used throughout the program.
It can hold value but not data. Therefore, It can hold multiple types of data within a
it is dataless. single object.
There is no time complexity in the case of In data structure objects, time complexity
data types. plays an important role.
Data type examples are int, float, double, Data structure examples are stack, queue,
etc. tree, etc.
• Linear data structure: Data structure in which data elements are arranged
sequentially or linearly, where each element is attached to its previous and next
adjacent elements, is called a linear data structure.
Examples of linear data structures are array, stack, queue, linked list, etc.
o Static data structure: Static data structure has a fixed memory size. It is
easier to access the elements in a static data structure.
An example of this data structure is an array.
o Dynamic data structure: In the dynamic data structure, the size is not fixed.
It can be randomly updated during the runtime which may be considered
efficient concerning the memory (space) complexity of the code.
Examples of this data structure are queue, stack, etc.
• Non-linear data structure: Data structures where data elements are not placed
sequentially or linearly are called non-linear data structures. In a non-linear data
structure, we can’t traverse all the elements in a single run only.
Examples of non-linear data structures are trees and graphs .
Arrays:
• An array is a linear data structure and it is a collection of items stored at contiguous
memory locations. The idea is to store multiple items of the same type together in
one place. It allows the processing of a large amount of data in a relatively short
period. The first element of the array is indexed by a subscript of 0. There are
different operations possible in an array, like Searching, Sorting, Inserting,
Traversing, Reversing, and Deleting.
➢ Characteristics of an Array:
An array has various characteristics which are as follows:
• Homogeneous Elements: All elements within an array must be of the same data type.
• Contiguous Memory Allocation: In most programming languages, elements in an
array are stored in contiguous (adjacent) memory locations.
• Zero-Based Indexing: In many programming languages, arrays use zero-based
indexing, which means that the first element is accessed with an index of 0, the
second with an index of 1, and so on.
• Random Access: Arrays provide constant-time (O(1)) access to elements. This means
that regardless of the size of the array, it takes the same amount of time to access
any element based on its index.
• Arrays use an index-based data structure which helps to identify each of the elements
in an array easily using the index.
• If a user wants to store multiple values of the same data type, then the array can be
utilized efficiently.
• An array can also handle complex data structures by storing data in a two-dimensional
array.
• An array is also used to implement other data structures like Stacks, Queues, Heaps,
Hash tables, etc.
• The search process in an array can be done very easily.
• Accessing elements: Elements in an array can be accessed by their index, which starts
from 0 and goes up to the size of the array minus one.
• Searching for elements: Arrays can be searched for a specific element using linear
search or binary search algorithms.
• Sorting elements: Elements in an array can be sorted in ascending or descending
order using algorithms like bubble sort, insertion sort, or quick sort.
• Inserting elements: Elements can be inserted into an array at a specific location, but
this operation can be time-consuming because it requires shifting existing elements in
the array.
• Deleting elements: Elements can be deleted from an array by shifting the elements
that come after it to fill the gap.
• Updating elements: Elements in an array can be updated or modified by assigning a
new value to a specific index.
• Traversing elements: The elements in an array can be traversed in order, visiting each
element once.
➢ Applications of Array:
Different applications of an array are as follows:
• An array is used in solving matrix problems.
• Database records are also implemented by an array.
• It helps in implementing a sorting algorithm.
• It is also used to implement other data structures like Stacks, Queues, Heaps, Hash
tables, etc.
• An array can be used for CPU scheduling.
• Can be applied as a lookup table in computers.
• Arrays can be used in speech processing where every speech signal is an array.
• The screen of the computer is also displayed by an array. Here we use a
multidimensional array.
• The array is used in many management systems like a library, students, parliament,
etc.
• The array is used in the online ticket booking system. Contacts on a cell phone are
displayed by this array.
• In games like online chess, where the player can store his past moves as well as
current moves. It indicates a hint of position.
• To save images in a specific dimension in the android Like 360*1200
➢ Real-Life Applications of Array:
• An array is frequently used to store data for mathematical computations.
• It is used in image processing.
• It is also used in record management.
• Book pages are also real-life examples of an array.
• It is used in ordering boxes as well.
➢ Types of arrays:
• One-Dimensional Array: This is the simplest form of an array, which consists of a
single row of elements, all of the same data type. Elements in a 1D array are accessed
using a single index.
• Multi-Dimensional Array: Arrays can have more than two dimensions, leading to
multi-dimensional arrays. These are used when data needs to be organized in a multi-
dimensional grid.
2. Linked List
A Linked List is a linear data structure which looks like a chain of nodes, where each node
contains a data field and a reference(link) to the next node in the list. Unlike Arrays,
Linked List elements are not stored at a contiguous location.
Common Features of Linked List:
• Node: Each element in a linked list is represented by a node, which contains two
components:
o Data: The actual data or value associated with the element.
o Next Pointer(or Link): A reference or pointer to the next node in the linked
list.
• Head: The first node in a linked list is called the “head.” It serves as the starting point
for traversing the list.
• Tail: The last node in a linked list is called the “tail.”
Types of Linked Lists:
• Singly-linked list
• Doubly linked list
• Circular linked list
• Doubly circular linked list
A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle,
meaning that the last element added to the stack is the first one to be removed.
➢ Types of Stacks:
• Fixed Size Stack: As the name suggests, a fixed size stack has a fixed size and cannot
grow or shrink dynamically. If the stack is full and an attempt is made to add an
element to it, an overflow error occurs. If the stack is empty and an attempt is made
to remove an element from it, an underflow error occurs.
• Dynamic Size Stack: A dynamic size stack can grow or shrink dynamically. When the
stack is full, it automatically increases its size to accommodate the new element, and
when the stack is empty, it decreases its size. This type of stack is implemented using
a linked list, as it allows for easy resizing of the stack.
➢ Stack Operations:
• push(): When this operation is performed, an element is inserted into the stack.
• pop(): When this operation is performed, an element is removed from the top of the
stack and is returned.
• top(): This operation will return the last inserted element that is at the top without
removing it.
• size(): This operation will return the size of the stack i.e. the total number of elements
present in the stack.
• isEmpty(): This operation indicates whether the stack is empty or not.
Characteristics of a Stack:
Stack has various different characteristics which are as follows:
• Stack is used in many different algorithms like Tower of Hanoi, tree traversal,
recursion, etc.
• Stack is implemented through an array or linked list.
• It follows the Last In First Out operation i.e., an element that is inserted first will pop
in last and vice versa.
• The insertion and deletion are performed at one end i.e. from the top of the stack.
• In stack, if the allocated space for the stack is full, and still anyone attempts to add
more elements, it will lead to stack overflow.
Applications of Stack:
Different applications of Stack are as follows:
• The stack data structure is used in the evaluation and conversion of arithmetic
expressions.
• It is used for parenthesis checking.
• While reversing a string, the stack is used as well.
• Stack is used in memory management.
• It is also used for processing function calls.
• The stack is used to convert expressions from infix to postfix.
• The stack is used to perform undo as well as redo operations in word processors.
• The stack is used in virtual machines like JVM.
• The stack is used in the media players. Useful to play the next and previous song.
• The stack is used in recursion operations.
➢ Types of Queue:
• Input Restricted Queue: This is a simple queue. In this type of queue, the input can
be taken from only one end but deletion can be done from any of the ends.
• Output Restricted Queue: This is also a simple queue. In this type of queue, the input
can be taken from both ends but deletion can be done from only one end.
• Circular Queue: This is a special type of queue where the last position is connected
back to the first position. Here also the operations are performed in FIFO order. To
know more refer this.
• Double-Ended Queue (Dequeue): In a double-ended queue the insertion and
deletion operations, both can be performed from both ends. To know more refer this.
• Priority Queue: A priority queue is a special queue where the elements are accessed
based on the priority assigned to them. To know more refer this.
➢ Operation performed on queue:
• Enqueue(): Adds (or stores) an element to the end of the queue..
• Dequeue(): Removal of elements from the queue.
• Peek() or front(): Acquires the data element available at the front node of the queue
without deleting it.
• rear(): This operation returns the element at the rear end without removing it.
• isFull(): Validates if the queue is full.
• isNull(): Checks if the queue is empty.
➢ Characteristics of a Queue:
• A tree is a non-linear and hierarchical data structure where the elements are
arranged in a tree-like structure. In a tree, the topmost node is called the root
node. Each node contains some data, and data can be of any type. It consists of a
central node, structural nodes, and sub-nodes which are connected via edges.
Different tree data structures allow quicker and easier access to the data as it is a
non-linear data structure. A tree has various terminologies like Node, Root, Edge,
Height of a tree, Degree of a tree, etc.
➢ There are different types of Tree-like
1) Binary Tree,
2) Binary Search Tree,
3) AVL Tree,
4) B-Tree, etc.
➢ Characteristics of a Tree:
The tree has various different characteristics which are as follows:
• A tree is also known as a Recursive data structure.
• In a tree, the Height of the root can be defined as the longest path from the root
node to the leaf node.
• In a tree, one can also calculate the depth from the top to any node. The root node
has a depth of 0.
➢ Applications of Tree:
Different applications of Tree are as follows:
• Heap is a tree data structure that is implemented using arrays and used to implement
priority queues.
• B-Tree and B+ Tree are used to implement indexing in databases.
• Syntax Tree helps in scanning, parsing, generation of code, and evaluation of
arithmetic expressions in Compiler design.
• K-D Tree is a space partitioning tree used to organize points in K-dimensional space.
• Spanning trees are used in routers in computer networks.
➢ Operation performed on tree:
A tree is a non-linear data structure that consists of nodes connected by edges. Here
are some common operations performed on trees:
• Insertion: New nodes can be added to the tree to create a new branch or to increase
the height of the tree.
• Deletion: Nodes can be removed from the tree by updating the references of the
parent node to remove the reference to the current node.
• Search: Elements can be searched for in a tree by starting from the root node and
traversing the tree based on the value of the current node until the desired node is
found.
• Traversal: The elements in a tree can be traversed in several different ways, including
in-order, pre-order, and post-order traversal.
• Height: The height of the tree can be determined by counting the number of edges
from the root node to the furthest leaf node.
• Depth: The depth of a node can be determined by counting the number of edges
from the root node to the current node.
• Balancing: The tree can be balanced to ensure that the height of the tree is
minimized and the distribution of nodes is as even as possible.
➢ Binary Tree:
• 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.
❖ The above tree is AVL because the differences between the heights of left and right
subtrees for every node are less than or equal to 1.
➢ Operations on an AVL Tree:
• Insertion
• Deletion
• Searching [It is similar to performing a search in BST]
➢ Rotating the subtrees in an AVL Tree:
An AVL tree may rotate in one of the following four ways to keep itself balanced:
➢ Left Rotation:
When a node is added into the right subtree of the right subtree, if the tree gets out of
balance, we do a single left rotation.
➢ Right Rotation:
If a node is added to the left subtree of the left subtree, the AVL tree may get out of
balance, we do a single right rotation.
➢ Left-Right Rotation:
A left-right rotation is a combination in which first left rotation takes place after that right
rotation executes.
➢ Right-Left Rotation:
A right-left rotation is a combination in which first right rotation takes place after that left
rotation executes.
➢ Advantages of AVL Tree:
1. AVL trees can self-balance themselves and therefore provides time complexity as
O(Log n) for search, insert and delete.
2. It is a BST only (with balancing), so items can be traversed in sorted order.
3. Since the balancing rules are strict compared to Red Black Tree, AVL trees in general
have relatively less height and hence the search is faster.
4. AVL tree is relatively less complex to understand and implement compared to Red
Black Trees.
➢ Disadvantages of AVL Tree:
1. It is difficult to implement compared to normal BST and easier compared to Red Black
2. Less used compared to Red-Black trees.
3. Due to its rather strict balance, AVL trees provide complicated insertion and removal
operations as more rotations are performed.
➢ Applications of AVL Tree:
1. AVL Tree is used as a first example self balancing BST in teaching DSA as it is easier to
understand and implement compared to Red Black
2. Applications, where insertions and deletions are less common but frequent data
lookups along with other operations of BST like sorted traversal, floor, ceil, min and
max.
3. Red Black tree is more commonly implemented in language libraries like map in
C++, set in C++, TreeMap in Java and TreeSet in Java.
4. AVL Trees can be used in a real time environment where predictable and consistent
performance is required.
➢ Red-Black Tree:
• A Red-Black Tree is a self-balancing binary search tree where each node has an
additional attribute: a color, which can be either red or black. The primary objective
of these trees is to maintain balance during insertions and deletions, ensuring
efficient data retrieval and manipulation.
• Binary search trees are a fundamental data structure, but their performance can
suffer if the tree becomes unbalanced. Red Black Trees are a type of balanced binary
search tree that use a set of rules to maintain balance, ensuring logarithmic time
complexity for operations like insertion, deletion, and searching, regardless of the
initial shape of the tree. Red Black Trees are self-balancing, using a simple color-
coding scheme to adjust the tree after each modification.
➢ Properties of Red-Black Trees:
1. Search O(log n)
2. Insert O(log n)
3. Delete O(log n)
1. Search O(log n)
2. Insert O(log n)
3. Delete O(log n)
➢ Properties of B-Tree:
• All leaves are at the same level.
• B-Tree is defined by the term minimum degree ‘t‘. The value of ‘t‘ depends upon disk
block size.
• Every node except the root must contain at least t-1 keys. The root may contain a
minimum of 1 key.
• All nodes (including root) may contain at most (2*t – 1) keys.
• Number of children of a node is equal to the number of keys in it plus 1.
• All keys of a node are sorted in increasing order. The child between two
keys k1 and k2 contains all keys in the range from k1 and k2.
• B-Tree grows and shrinks from the root which is unlike Binary Search Tree. Binary
Search Trees grow downward and also shrink from downward.
• Like other balanced Binary Search Trees, the time complexity to search, insert, and
delete is O(log n).
• Insertion of a Node in B-Tree happens only at Leaf Node.
Search is similar to the search in Binary Search Tree. Let the key to be searched is k.
• Start from the root and recursively traverse down.
• For every visited non-leaf node,
o If the node has the key, we simply return the node.
o Otherwise, we recur down to the appropriate child (The child which is just
before the first greater key) of the node.
• If we reach a leaf node and don’t find k in the leaf node, then return NULL.
Examples:
Input: Search 120 in the given B-Tree.
Solution:
➢ Applications of B-Trees:
• It is used in large databases to access data stored on the disk
• Searching for data in a data set can be achieved in significantly less time using the B-
Tree
• With the indexing feature, multilevel indexing can be achieved.
• Most of the servers also use the B-tree approach.
• B-Trees are used in CAD systems to organize and search geometric data.
• B-Trees are also used in other areas such as natural language processing, computer
networks, and cryptography.
➢ Advantages of B-Trees:
• B-Trees have a guaranteed time complexity of O(log n) for basic operations like
insertion, deletion, and searching, which makes them suitable for large data sets and
real-time applications.
• B-Trees are self-balancing.
• High-concurrency and high-throughput.
• Efficient storage utilization.
➢ Disadvantages of B-Trees:
• B-Trees are based on disk-based data structures and can have a high disk usage.
• Not the best for all cases.
• Slow in comparison to other data structures.
➢ B+ Tree:
• B + Tree is a variation of the B-tree data structure. In a B + tree, data pointers are
stored only at the leaf nodes of the tree. In a B+ tree structure of a leaf node
differs from the structure of internal nodes. The leaf nodes have an entry for every
value of the search field, along with a data pointer to the record (or to the block
that contains this record).
• The leaf nodes of the B+ tree are linked together to provide ordered access to the
search field to the records. Internal nodes of a B+ tree are used to guide the
search. Some search field values from the leaf nodes are repeated in the internal
nodes of the B+ tree.
➢ Features of B+ Trees:
• Balanced: B+ Trees are self-balancing, which means that as data is added or removed
from the tree, it automatically adjusts itself to maintain a balanced structure. This
ensures that the search time remains relatively constant, regardless of the size of the
tree.
• Multi-level: B+ Trees are multi-level data structures, with a root node at the top and
one or more levels of internal nodes below it. The leaf nodes at the bottom level
contain the actual data.
• Ordered: B+ Trees maintain the order of the keys in the tree, which makes it easy to
perform range queries and other operations that require sorted data.
• Fan-out: B+ Trees have a high fan-out, which means that each node can have many
child nodes. This reduces the height of the tree and increases the efficiency of
searching and indexing operations.
• Cache-friendly: B+ Trees are designed to be cache-friendly, which means that they
can take advantage of the caching mechanisms in modern computer architectures to
improve performance.
• Disk-oriented: B+ Trees are often used for disk-based storage systems because they
are efficient at storing and retrieving data from disk.
➢ Why Use B+ Tree?
• B+ Trees are the best choice for storage systems with sluggish data access because
they minimize I/O operations while facilitating efficient disc access.
• B+ Trees are a good choice for database systems and applications needing quick data
retrieval because of their balanced structure, which guarantees predictable
performance for a variety of activities and facilitates effective range-based queries.
➢ Difference Between B+ Tree and B Tree:
Some differences between B+ Tree and B Tree are stated below.
B Tree
Parameters B+ Tree
Diagram-II Using the Pnext pointer it is viable to traverse all the leaf nodes, just like a linked
list, there by achieving ordered access to the records stored in the disk.
➢ Advantages of B+Trees:
• A B+ tree with ‘l’ levels can store more entries in its internal nodes compared to a B-
tree having the same ‘l’ levels. This accentuates the significant improvement made to
the search time for any given key. Having lesser levels and the presence of
Pnext pointers imply that the B+ trees is very quick and efficient in accessing records
from disks.
• Data stored in a B+ tree can be accessed both sequentially and directly.
• It takes an equal number of disk accesses to fetch records.
• B+trees have redundant search keys, and storing search keys repeatedly is not
possible.
➢ Disadvantages of B+ Trees:
• The major drawback of B-tree is the difficulty of traversing the keys sequentially. The
B+ tree retains the rapid random access property of the B-tree while also allowing
rapid sequential access.
➢ Preorder Traversal of Binary Tree:
Preorder traversal is defined as a type of tree traversal that follows the Root-Left-Right
policy where:
➢ Complexity Analysis:
Time Complexity: O(N) where N is the total number of nodes. Because it traverses all the
nodes at least once.
Auxiliary Space:
• O(1) if no recursion stack space is considered.
• Otherwise, O(h) where h is the height of the tree
• In the worst case, h can be the same as N (when the tree is a skewed tree)
• In the best case, h can be the same as logN (when the tree is a complete tree)
If we perform a preorder traversal in this binary tree, then the traversal will be as follows:
Step 1: At first the root will be visited, i.e. node 1.
Node 1 is visited
Step 2: After this, traverse in the left subtree. Now the root of the left subtree is visited i.e.,
node 2 is visited.
Node 2 is visited
Step 3: Again the left subtree of node 2 is traversed and the root of that subtree i.e., node 4
is visited.
Node 4 is visited
Step 4: There is no subtree of 4 and the left subtree of node 2 is visited. So now the right
subtree of node 2 will be traversed and the root of that subtree i.e., node 5 will be visited.
Node 5 is visited
Step 5: The left subtree of node 1 is visited. So now the right subtree of node 1 will be
traversed and the root node i.e., node 3 is visited.
Node 3 is visited
Step 6: Node 3 has no left subtree. So the right subtree will be traversed and the root of the
subtree i.e., node 6 will be visited. After that there is no node that is not yet traversed. So
the traversal ends.
Inorder traversal is defined as a type of tree traversal technique which follows the Left-
Root-Right pattern, such that:
Time Complexity: O(N) where N is the total number of nodes. Because it traverses all the
nodes at least once.
Auxiliary Space: O(h) where h is the height of the tree. This space is required for recursion
calls.
• In the worst case, h can be the same as N (when the tree is a skewed tree)
• In the best case, h can be the same as log N (when the tree is a complete tree
If we perform an inorder traversal in this binary tree, then the traversal will be as follows:
Step 1: The traversal will go from 1 to its left subtree i.e., 2, then from 2 to its left subtree
root, i.e., 4. Now 4 has no left subtree, so it will be visited. It also does not have any right
subtree. So no more traversal from 4
Node 4 is visited
Step 2: As the left subtree of 2 is visited completely, now it read data of node 2 before
moving to its right subtree.
Node 2 is visited
Step 3: Now the right subtree of 2 will be traversed i.e., move to node 5. For node 5 there is
no left subtree, so it gets visited and after that, the traversal comes back because there is no
right subtree of node 5.
Node 5 is visited
Step 4: As the left subtree of node 1 is, the root itself, i.e., node 1 will be visited.
Node 1 is visited
Step 5: Left subtree of node 1 and the node itself is visited. So now the right subtree of 1 will
be traversed i.e., move to node 3. As node 3 has no left subtree so it gets visited.
Node 3 is visited
Step 6: The left subtree of node 3 and the node itself is visited. So traverse to the right
subtree and visit node 6. Now the traversal ends as all the nodes are traversed.
Postorder traversal is defined as a type of tree traversal which follows the Left-Right-Root
policy such that for each node:
Time Complexity: O(N) where N is the total number of nodes. Because it traverses all the
nodes at least once.
Auxiliary Space: O(1) if no recursion stack space is considered. Otherwise, O(h) where h is
the height of the tree
• In the worst case, h can be the same as N (when the tree is a skewed tree)
• In the best case, h can be the same as logN (when the tree is a complete tree)
If we perform a postorder traversal in this binary tree, then the traversal will be as follows:
Step 1: The traversal will go from 1 to its left subtree i.e., 2, then from 2 to its left subtree
root, i.e., 4. Now 4 has no subtree, so it will be visited.
Node 4 is visited
Step 2: As the left subtree of 2 is visited completely, now it will traverse the right subtree of
2 i.e., it will move to 5. As there is no subtree of 5, it will be visited.
Node 5 is visited
Step 3: Now both the left and right subtrees of node 2 are visited. So now visit node 2 itself.
Node 2 is visited
Step 4: As the left subtree of node 1 is traversed, it will now move to the right subtree root,
i.e., 3. Node 3 does not have any left subtree, so it will traverse the right subtree i.e., 6. Node
6 has no subtree and so it is visited.
Node 6 is visited
Step 5: All the subtrees of node 3 are traversed. So now node 3 is visited.
Node 3 is visited
Step 6: As all the subtrees of node 1 are traversed, now it is time for node 1 to be visited and
the traversal ends after that as the whole tree is traversed.