0 ratings0% found this document useful (0 votes) 87 views112 pagesUnit 3 Long
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
External Sorting Algorithm
era Tn Nm eos (MTOM Me (atl Rom ULM ey-T\(e)
operations in a binary search tree (BST):
Pal
Mane mena
= Start at the root node.
= Compare the new element with the
crit aialelel SRI
em RUN ae rT RT)
Tn alee RCI Me RoR Mit
child.
BeAr eee TC en ett)
current node's value, move to the right
foililen
Peele et eT) ual slimceled
is found, and insert the new element
Toro
ey ONS anal} anything...
© scanned with OKEN ScannerExternal Sorting Algorithm
YAEL
BOR T-cell eo
i Tag-la Ul -acolelaalols
Compare the target element with the
eaters Re
If they match, the search is successful.
If the target element is less than the
current node's value, move to the left
ile
If the target element is greater than the
current node's value, move to the right
eile
Repeat the process until the target
element is found or a null node is
reached.
ey Ask me anything...
© scanned with OKEN Scanner— External Sorting Algorithm
3. Deletion:
To delete an element from the BST:
CSc Ra OL Ale
PRU Role Lao
= If the node has no children, simply
remove it.
= If the node has one child, replace it
Ue
= If the node has two children, find
the in-order successor (or
predecessor), replace the node’s
value with the successor’s value,
and recursively delete the
successor.
CPC
Traversal refers to visiting all nodes in the
ey Ask me anything... (a) d
© scanned with OKEN Scanner= External Sorting Algorithm
CLC Or LH
Traversal refers to visiting all nodes in the
BST in a specific order.
Common traversal methods include
CR Rie liek ma
node, right subtree (sorted order).
Pe aU eel nanos (mis
subtree, right subtree (used for copying
trees),
= Post-order: Visit left subtree, right
subtree, current node (used for deleting
a
BST operations are essential for maintaining the
tree's properties and efficiently searching,
inserting, and deleting elements. Properly
balanced BSTs ensure logarithmic time
complexity for these operations 1 2) 34,
1 Reeser ee oe
2 [B tutorialspointcom | +3 more
Pee ORCA) Poe
6 Ask me anything...
© scanned with OKEN Scannereines es
From testbook.com — deliv:
is the Binary Search Tree (BST)
HAN MUR, Ge BUSH PuNTeH rat uuu sera.
In this mathematics article, we will explore the Binary
Search Tree. It will be a valuable resource for students
with a technical background, as it covers an essential
topic in their coursework and provides helpful
information.
What is a Tree?
A tree is a special type of data structure that organizes
data in a hierarchical manner. It's like a family tree,
where each person represents a node and is connected
to other family members. In this data structure, nodes
are used to store different objects or entities, and they
are connected to one another to create a hierarchical
structure.
The unique thing about a tree is that it doesn't store
data ina straight line or ina particular order. Instead, it
arranges the data in a branching pattern, allowing for
easy navigation and organization. So, a tree is a non-
linear data structure that efficiently represents
relationships and hierarchies between various
elements
een r Ey
© scanned with OKEN ScannerWhat is Binary Search Tree?
In a binary search tree, the elements are arranged
following a specific order. The rule is that the value of a
left node must be smaller than its parent node, and the
value of a right node must be greater than its parent
node. This rule is repeated over and over again for the
left and right parts of the tree, starting from the main
starting point called the root.
Let's explore the idea of Binary Search Trees by looking
at an example.
® testbook
Looking at the diagram, we can see that the main node
is 40. Notice that all the nodes on the left side are
smaller than the main node, while all the nodes on the
right side are bigger.
In the same way, we can observe that the left child of
the root node is bigger than its own left child and
smaller than its right child. This means that the tree
shown in the image follows the rules of a binary
tree. Hence, we can conclude that the tree in the
image is a binary search tree.
© scanned with OKEN Scannerimage is a binary search tree.
If we change the value of node 35 to 55 in the tree
mentioned earlier, let's determine whether the resulting
tree will still be a binary search tree or not.
ws Zs
25 5545 60
In the tree shown, the main value at the top is 40. It is
larger than its left child, which is 30, but smaller than
the right child of 30, which is 55. Because of this, the
tree doesn't follow the rule of a Binary Search Tree. So,
we can conclude that the tree is not a Binary Search
Tree,
To learn about the faces, edges and vertices for
different shapes with examples.
testbook At
Get Unlimited Access to Test Series ‘©
860+ Exams and much more.
CAE}
© scanned with OKEN ScannerBinary Search Tree Operations
Binary Search Tree (BST) operations involve various
actions performed on a BST data structure. Here are
the key operations associated with BSTs:
1. Insertion:
+ Adding a new node with a given key value into the
BST while maintaining the BST property.
+ Compare the key value with the current node and
traverse left or right until finding an appropriate
spot to insert the new node.
2. Search
+ Finding a specific key value within the BST.
* Start from the root node and compare the target
key with the current node's key.
+ Move left or right in the tree based on the
comparison until finding a match or reaching a leaf
node
3. Deletion:
« Removing a node with a specific key value from the
BST.
+ Handle different scenarios: a node has no chi
anode has one child, or a node has two child!
+ Reorganize the tree while maintaining the BST
pe CRN)
© scanned with OKEN Scanneranode has one child, or a node has two children.
+ Reorganize the tree while maintaining the BST
property.
4. Traversal:
* Visiting and processing all the nodes in the BST in a
specific order.
+ Common traversal methods include Inorder (left-
root-right), Preorder (root-left-right), and Postorder
(left-right-root),
5. Minimum/Maximum:
* Finding the node with the minimum or maximum
key value in the BST.
* Traverse to the leftmost node for the minimum
value or the rightmost node for the maximum value.
6. Successor/Predecessor:
+ Finding the node with the next smallest or next
largest key value in the BST.
+ For the successor, go to the right child and then find
the leftmost node.
« For the predecessor, go to the left child and then
find the rightmost node
7. Height/Size: ©
* Determining the height of the BST, which is the
Peat)
© scanned with OKEN Scanner7. Height/Size:
+ Determining the height of the BST, which is the
maximum number of edges from the root to a leaf
node.
+ Counting the number of nodes in the BST.
These operations allow manipulation, searching, and
analysis of data within a Binary Search Tree, making it a
versatile data structure for efficient organization and
retrieval of information.
To learn about the adjacency matrix, how to create an
adjacency matrix with examples.
Test Series
4 4.1K STUDENTS
All SET Exams Mock Test
109 TOTAL TESTS | 1 Free Tests
rapter Test
6 Full Tests
30 Official Chapter Tests ©
33 Previous Years Papers
© scanned with OKEN ScannerTime Complexity of Binary Search Tree
The time complexity of various operations in a Binary
Search Tree (BST) depends on the tree's structure and
balance.
Search:
+ Ina balanced BST, the time complexity for
searching an element is O(log(n)) where 72 is
the number of nodes in the tree. This efficiency is
achieved by halving the search space at each level
as we compare the target value with the current
node's value and proceed left or right.
In an unbalanced BST, the worst-case time
complexity for searching can be O(n: if the tree is
completely skewed, as each node needs to be
traversed in a linear fashion.
Insertion:
+ Ina balanced BST, the time complexity for inserting
an element is also O(log(1)) since we follow a
similar process to searching, finding the appropriate
position to insert the new node while maintaining
the BST property.
+ In an unbalanced BST, the worst-case time
complexity for insertion can be O(72) if the ©
highly unbalanced, as each node may need to be
© scanned with OKEN Scannerthe BST property.
+ In an unbalanced BST, the worst-case time
complexity for insertion can be (7) if the tree is
highly unbalanced, as each node may need to be
traversed before finding the proper position.
Deletion:
« Similar to insertion, the time complexity for
deletion in a balanced BST is O(log(n)) on
average,
* In an unbalanced BST, the worst-case time
complexity for deletion can be O(n) if the tree is
highly unbalanced and requires extensive
restructuring.
Binary Search Tree Algorithm
Now, we will explore the algorithm for searching an
element in a Binary Search Tree. The steps
* Search (root, item)
* Step 1 - if (item = root > data) or (root = NULL)
* return root
+ else if (item < root > data)
* return Search(root = left, item)
+ else
* return Search(root > right, item)
+ END if ©
+ Step 2-END
© scanned with OKEN ScannerBalanced Binary Search Tree
A Balanced Binary Search Tree (BST) is a type of binary
search tree that maintains a balanced structure to
ensure efficient operations. In a balanced BST, the
heights of the left and right subtrees of any node differ
by at most a specific value (often 1). An Balanced
Binary Search Tree, also known as a Optimal Binary
Search Tree.
There are several commonly used balanced BST
variants, including AVL trees and Red-Black trees. These
tree structures employ different balancing techniques
to maintain balance during insertions and deletions.
For example, let's consider an AVL Tree, which is a type
of Balanced Binary Search Tree.
Suppose we want to insert the following elements into
an AVL Tree in the given order:
10, 20, 30, 40, 50, 60, 70
+ Insert 10 as the root node.
+ Insert 20 as the right child of 10.
+ Insert 30 as the right child of 20.
+ Insert 40 as the right child of 30, causing an
imbalance.
+ Perform a left rotation at 30) to balance the tree
+ Insert 5Q as the right child of 40.
+ Insert 60 as the right child of 50, causing an
imbalance.
+ Perform a left rotation at 4Q and a right rotat}
50 to balance the tree.
+ Insert 70 as the right child of 60.
© scanned with OKEN ScannerThe resulting AVL Tree will look like this:
& testbook
In this AVL Tree, the heights of the left and right
subtrees of each node differ by at most one,
maintaining the balanced property. The tree's balance
ensures efficient operations with a time complexity of
O(log(n)), where n is the number of nodes in the
tree.
Binary Search Tree Implementation
Now, let's examine a program that implements the
operations of a Binary Search Tree. Here is a basic
implementation of a Binary Search Tree (BST) in
Python
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None ©
self.right = None
pee RU
© scanned with OKEN ScannerProperties of Binary Search Tree
Some of the important properties of binary search tree
(BST) are listed below:
+ BST is a hierarchical data structure.
+ Each node in a BST has a key value and two child
pointers.
* The key value of the left child is always smaller than
the parent's key.
* The key value of the right child is always larger than
the parent's key.
+ BST allows for efficient searching and sorting
operations.
* BSTs maintain an ordered structure, making it easy
to find elements
+ The left subtree of a node contains keys smaller
than the node's key.
* The right subtree of a node contains keys greater
than the node's key.
* BSTs can be used for efficient insertion and
deletion of elements.
« The structure of a BST affects the time complexity
of operations.
Advantages of Binary Search Tree
Advantages of binary search trees are listed below:
fast search operations due to their organized
structure.
* Sorted Data: The elements in a Binary Search Tree
Cred
+ Efficient Searching: Binary Search Trees rei
© scanned with OKEN Scanner* Sorted Data: The elements in a Binary Search Tree
are automatically sorted, making it easier to retrieve
data in a specific order
* Easy Insertion and Deletion: Adding or removing
elements from a Binary Search Tree is relatively
simple and efficient.
+ Memory Efficiency: Binary Search Trees use
memory efficiently by dynamically allocating
memory for new nodes only when necessary.
To learn about the distance between points, their
formula and derivation with examples.
Application of Binary Search Tree
Some of the applications of binary search trees listed
below:
* Dictionary: BSTs are commonly used to implement
dictionaries, allowing efficient word lookup and
spell-checking.
+ Database Indexing: BSTs enable fast data retrieval
by serving as index structures in databases.
+ File System: BSTs can be utilized in file systems to
organize and search files efficiently.
+ Auto-complete: BSTs can power auto-complete
features in text editors or search engines,
suggesting relevant options as users type
+ Symbol Tables: BSTs are used to implement symbol
tables, facilitating efficient symbol lookup an
management in programming languages. ©
* Network Routing: BSTs can assist in network
routtina alaarithms aidina in efficient nacket
© scanned with OKEN ScannerIn this article v
What is Binary Tree in Data
Structure?
In computer science, a binary tree is a structurally
complete data structure in which each node has at
most two children. A binary tree usually has two.
nodes, called the left and right nodes, with the left
being less than the right. The topmost node in the tree
is called the root node. Binary trees are generally used
for quick storage and retrieval of data. Because each
node can only have two children, it is easy to find a
particular data piece without searching through the
entire structure. Additionally, binary trees can be
traversed using either a recursive or iterative
algorithm. As a result, a binary tree in the data
structure is often used when performance is critical,
such as in real-time applications.
Terminologies Associated with
Binary Trees
Here, we'll define some of the most important terms
you need to know to understand binary trees.
+ Binary Tree: A tree is a data structure that consists
of nodes connected bv edaes. A binarv tree is a type
Fast forward your career with 5004
CLAD sor-rsey courses 25S
ee eee gl
Get a 1:1 Mentorship call with our
ee rec)
CEC hing
© scanned with OKEN ScannerBinary Tree in Da... e fl
Pees aise
In this article v
Terminologies Associated with
Binary Trees
Here, we'll define some of the most important terms
you need to know to understand binary trees.
+ Binary Tree: A tree is a data structure that consists
of nodes connected by edges. A binary tree is a type
of tree in which each node has at most two child
nodes, often referred to as left and right child nodes.
* Root Node: The root node is the topmost node in a
tree. It doesn't have a parent node since it's at the
top of the tree.
* Child Node: A child node is any node with a parent
node. Each node can have at most two child nodes
ina binary tree.
ing Nodes: Sibling nodes are nodes that have the
same parent node. In other words, they're siblings.
* Ancestor Nodes: Ancestor nodes are defined in
terms of child nodes and parent nodes. An ancestor
node is any node that is higher up in the tree than a
given child node. For example, if Node Cis a child
node of Nade R then Node R ic an ancestor node of.
; 9
Fast forward your career with 5004 ro)
ax future-ready courses LJ 29 ee
alse
CER usa eel kd
eee eet ra)
(eC Cig
© scanned with OKEN ScannerIn this article v
+ Ancestor Nodes: Ancestor nodes are defined in
terms of child nodes and parent nodes. An ancestor
node is any node that is higher up in the tree than a
given child node. For example, if Node Cis a child
node of Node B, then Node B is an ancestor node of
Node C.
+ Descendant Nodes: Descendant nodes are also
defined in terms of child nodes and parent nodes. A
descendant node is any node that is lower down in
the tree than a given parent node. So, continuing
with our previous example, if Node Bis is a parent
node of Node C, then Node Cis a descendant node
of Node B.
+ Leaf Nodes: Leaf nodes are nodes that don't have
any children. In other words, they're at the bottom of
the tree!
+ Internal Nodes: Internal nodes are all nodes that are
not leaf nodes. Therefore, they're all non-leaf nodes
that have one or more child nodes.
+ Height: The height of a particular node is the
number of edges on the longest path from that node
to a leaf node. The tree's height is defined as the
height of the root node.
+ Depth: The depth of a node refers to its level in the
tree and is equal to the number of edges on the path
from th Fast forward your career with 500% e'
PRPAY) tuture-ready courses 2S
(OSB ee eke a
i ea)
CeCe nag
© scanned with OKEN ScannerIn this article v
Components of Binary Tree
Source
A binary tree is a data structure that allows two nodes
to be linked together by a path from the root to the
leftmost child and from the leftmost child to the
rightmost child. The different components of a binary
tree are the root, the left subtree, and the right
subtree.
1. The Root
The root of a binary tree is the topmost node in the
tree. The root node has no parents and is the ancestor
of all other nodes in the tree. The root node contains
data and links to its left and right children.
2. The Left Subtree
: Fast forward your career with 500+" t
_ future-ready courses [3219S
n : St
Get a 1:1 Mentorship call with our
Cee rec)
CEC om hig
© scanned with OKEN ScannerIn this article v
2. The Left Subtree
The left subtree is a binary tree that consists of all
nodes to the left of the root node. The left subtree's
root node is the left child of the original tree's root
node. All nodes in the left subtree are less than or
equal to the original tree's root node.
3. The Right Subtree
The right subtree is a binary tree that consists of all
nodes to the right of the root node. The right subtree's
root node is the right child of the original tree's root
node. All nodes in this subtree are greater than or
equal to the original tree's root node.
If you're working with binary trees, it's important to
understand the different components that make up
this data structure. By understanding the root, left
subtree, and right subtree, you'll be well on your way
to becoming a binary tree expert.
Properties of Binary Tree in Data
Structure
Here are some key properties of binary trees in the
data structure.
Fast forward your career with 500°
future-ready courses J 25S
ORC ee nat g
Sor oa
CTC ang
© scanned with OKEN ScannerIn this article v
Here are some key properties of binary trees in the
data structure.
+ Efficient Insertion and Deletion: One of the
advantages of using a binary tree is that insertion
and deletion can be done quite efficiently. If the
correct position for insertion or deletion is known,
then it can be done in O(log n) time. This is because
you only need to traverse down the tree to the
correct position.
+ Efficient Searching: Another feature of using a
binary tree is that searching can be done quite
efficiently as well. If the value searched for is known,
it can be found in O(log n) time. This is because you
only need to traverse down the tree until you find the
correct value.
+ Data Structure: A binary tree is also a very powerful
data structure. It can be used to store data in an
efficient way. For example, a binary tree can be used
to store information about a family tree. Each person
in the family would be represented by a node in the
tree, and the relations between them would be
represented by the edges between the nodes.
Types of Fast forward your career with 500%
future-ready courses JG S
Get a 1:1 Mentorship call with our
Cee cay
ETC ag
© scanned with OKEN Scannerae
In this article v
Types of Binary Tree
There are several different types of binary trees in the
data structure, each with its own characteristics. The
most common types are full binary tree, perfect binary
tree, complete binary tree, degenerate binary tree, &
balanced binary tree in the data structure. Let's take a
closer look at each one.
1. Full/Proper/Strict Binary Trees
A full or proper binary tree is a tree in which every
node has either zero or two child nodes. There are
exactly two child nodes for each internal node in a
strict binary tree.
2. Complete Binary Trees
" Fast forward your career with 500
; ae future-ready courses LJ 25S
Get a 1:1 Mentorship call with our
Cee ca)
ETC ag
© scanned with OKEN Scanneris}
In this article
2. Complete Binary Trees
A complete binary tree is a tree where all levels are
fully filled, with the exception of the last level, and all
nodes on the last level are as far left as possible.
3. Perfect Binary Trees
A perfect binary tree is a special type of complete
binary tree where every internal node has exactly two
children & all leaves are at the same level.
4. Degenerate Binary Tree
A degenerate or pathologic binary tree is one where
there exists only one path from the root to any leaf
node. In other words, it is a tree in which each node
has only one child node.
5. Balanced Binary Trees
A balanced tree in the data structure is one in which
the height of the right & left subtrees differ by at most
1 level and in which the left & right subtrees are also
evenly balanced. The height of a balanced tree with n
nodes is O (logn).
By understar Fast forward your career with 500 t
CE future-ready courses J 20S
needs. Moreover, to make your choice technicall
Get a 1:1 Mentorship call with our
Paice
ECC rts
© scanned with OKEN Scannerue
In this article v
Implementation of Binary Trees with
Examples
A binary tree refers to a data structure that allows the
two nodes to be easily linked together by a path from
the root to the leftmost child, known as the left path, &
from the leftmost child to the rightmost child, known
as the right path. The path is called a path because it
can be followed from one node to another. A binary
tree is thus defined as a finite set of nodes with the
following properties:
+ The data in each node is greater than all data in the
left subtree and less than all data in the right
subtree.
+ The left and right subtrees are themselves binary
trees.
Here we are now with the binary tree example in the
data structure. A binary tree can be represented by an
array in which the elements are stored in level order,
i.e., the root is at index 0, the left child of the root is at
index 1, the right child of the root is at index 2, and so
on. For example, an array [3, 9, 20, null, null, 15, 7]
represents the following binary tree:
Fast forward your career with 500%
=z future-ready courses 129
Get a 1:1 Mentorship call with our
ee cay
(ETC ag
© scanned with OKEN ScannerIn this article v
An empty binary tree is represented by an empty array
(1.
A full binary tree is a binary tree in which each node
has exactly two children. A perfect binary tree is a full
binary tree in which all leaves are at the same level.
3 Perfect Binary Tree Full Binary Tree
Complete Binary Tree
i\ 3 5
an a 15 ot 2 19 108 427 25
2930 26 24 28 20 18
7 aa an an a
Fast forward your career with 5004"
a future-ready courses [338
Get a 1:1 Mentorship call with our
era
CEO hig Ty
© scanned with OKEN ScannerIn this articte
What are th.
' Applications of Bj
Trees? Binary
of data. Additionally, binary trees can be used to
efficiently search through large amounts of data. For
example, if you were looking for a Specific word in a
dictionary, you could use a binary tree to find where
that word is located quickly.
Binary trees are also used in operating systems to
Manage memory allocation, When a new process is
created, it is stored in a memory block called a “page”,
Each page has a certain amount of memory allocated
to it. When the operating system needs to allocate
more memory to a Process, it will first check if any
available pages are large enough to satisfy the
request. The operating system will create a new page
and allocate the memory if there are no available
Pages. This process is much more efficient than
searching through all of the memory for an available
block of sufficient size; using a binary tree helps
reduce search time from O(n) (linear search) to O(log
n) (binary search).
ite Fast forward your career with 500+ |
Bs coer future-ready courses Jj 293
(OPC eRe Sa.
(orca eg
© scanned with OKEN ScannerIn this article v
Benefits of a Binary Tree in Data
Structure
There are many reasons why you might want to use a
binary tree over other data structures like arrays or
linked lists. Some advantages of binary trees in data
structure include the following:
+ Faster search time: Since each node in a binary tree
can be quickly accessed by its unique key, search
times are much faster than with other data
structures. For example, if you wanted to find a
specific record in an array, you would have to scan
through the entire array until you found the desired
record. With a binary tree, you can start at the root
node and quickly traverse the tree until you find the
desired record.
* Increased flexibility: Unlike an array, a binary tree is
not confined to being stored in sequential memory
locations. This means that binary trees can be easily
implemented on systems with limited memory
resources.
+ Efficient insertion and deletion: Insertion and
deletion operations can be performed on a binary
tree in Cfta~ 9) Hon vthaes = in the momboe of
Fast forward your career with 500%
future-ready courses j 28S
yorurese Uperauons un ant array.
Get a 1:1 Mentorship call with our
Ceca)
ETC ag
© scanned with OKEN ScannerIn this article v
+ Efficient insertion and deletion: Insertion and
deletion operations can be performed on a binary
tree in O(log n) time, where n is the number of nodes
in the tree. This is much faster than the O(n) time
required for these operations on an array.
* Reduced storage requirements: Since each node
only has two child pointers, a binary tree requires
less storage space than other data structures such
as an array or linked list.
Disadvantages of Binary Trees
Despite their advantages, there are also some
disadvantages associated with using binary trees:
* Difficult to implement: Since each node can only
have two children, it can be difficult to correctly
implement all the required functionality for a binary
tree (e.g,, inserting and deleting nodes).
* Limited to balancing algorithms: A binary tree can
become unbalanced if left unchecked, resulting in
decreased performance. Balancing algorithms (such
as AVL trees and red-black trees) can be used to
keep a binary tree balanced, but these algorithms
add cor
Fast forward your career with 500°
A| future-ready courses J 2S
Get a 1:1 Mentorship call with our
Ce hrs
Ces ay
© scanned with OKEN Scanner7
In this article ¥
as AVL trees and red-black trees) can be used to
keep a binary tree balanced, but these algorithms
add complexity to the implementation.
Conclusion
A tree data structure is one of the most powerful tools
that you can use to store and organize data. A binary
tree is a particularly efficient type of tree data
structure, which makes it an important tool for
computer science applications. This guide should have
given you a good understanding of what a binary tree
is, how it works, and how you can use it to store and
retrieve data. Moreover, you should also look to widen
your knowledge with a quality Java Certifi
ation
Course. With this knowledge in hand, you should be
able to start using binary trees in your projects.
Frequently Asked Questions (FAQs)
1. Whatis a binary tree traversal algorithm?
A binary tree traversal algorithm is an algorithm
used to visit all the nodes of a binary tree. The
order in which the nodes are visited can be
important Fast forward your career with 500 hy
future-ready courses JS
SORE LC hen ke
trea
COE
© scanned with OKEN ScannerUST]
freeCodeCamp (4)
Learn to code — free 3,001 fataa cael}
What is Tree Traversal?
Traversing a tree means visiting and
outputting the value of each node ina
particular order. In this tutorial, we will use
the Inorder, Preorder, and Post order tree
traversal methods.
The major importance of tree traversal is
that there are multiple ways of carrying
out traversal operations unlike linear data
structures like arrays, bitmaps, matrices
where traversal is done ina linear order.
Each of these methods of traversing a tree
have a particular order they follow:
* For Inorder, you traverse from the
left subtree to the root then to the
right subtree.
* For Preorder, you traverse from
the root to the left subtree then to
the right subtree.
—*_For Post order. vou traverce fram
© scanned with OKEN ScannerfreeCodeCamp (A)
Learn to code — free 3,000-hour
¢ For Post order, you traverse from
the left subtree to the right
subtree then to the root.
Here is another way of representing the
information above:
Inorder => Left, Root, Right.
Preorder => Root, Left, Right.
Post order => Left, Right, Root.
How to Traverse a Tree Using
Inorder Traversal
We are going to create a tree similar to the
one in the last section, but this time the
node keys will be numbers instead of
letters.
Remember that the values of the nodes on
the left subtree are always smaller than the
value of the root node. Also, the values of
© scanned with OKEN ScannerfreeCodeCamp (4)
Re Tah Koos (Bem c-Rel melt]
Remember that the values of the nodes on
the left subtree are always smaller than the
value of the root node. Also, the values of
the nodes on the right subtree are larger
than the value of the root node.
Here is the diagram we will be working
with:
Recall that the order for inorder traversal
is Left, Root, Right.
This is the result we get after using inorder
traversal:
© scanned with OKEN Scanner10:38
freeCodeCamp (A)
TUR Kool Ram ic AO Om iol mal eal}
D,B,E,A,F,C,G
If that seems a bit complex for you to
understand, then follow the order of the
colors in the picture below
Inorder traversal
How to Traverse a Tree Using
Preorder Traversal
The order here is Root, Left, Right.
Using the same diagram above, we have:
(ities
© scanned with OKEN ScannerfreeCodeCamp (A)
TUL le Bem ice n etme mee gael Ola)
A,B,D,E,C,F,G
Here is the same diagram with different
colors used as a guide:
Preorder traversal
How to Traverse a Tree Using
Postorder Traversal
The order for post order traversal is Left,
Right, Root.
Here is the output:
D,E,B,F,G,C,A
ee
© scanned with OKEN Scannera 4
freeCodeCamp (A)
ee TR Nels Ream eR mM aa OTA)
If you can't figure out how we arrived at
that result, then use the colors in the
picture below as a guide:
Postorder traversal
Conclusion
In this tutorial, we learned the basics of
what a binary search tree is, what the
various parts of a binary tree are, and the
common terms associated with a tree. We
also saw some of the algorithms we can use
to traverse a tree.
Thank vou for reading!
© scanned with OKEN ScannerBLU) 8 2}
freeCodeCamp (A)
Peta R laos Sem ieaRU mie mete sel Ty
What Is a Binary Search
Tree?
A binary search tree is a binary tree made
up of nodes. Each node has a key signifying
its value.
The value of the nodes on the left subtree
are smaller than the value of the root node.
And the value of the nodes on the right
subtree are larger than the value of the
root node.
The root node is the parent node of both
subtrees.
The diagram below shows the main parts
of a binary tree:
© scanned with OKEN ScannerBLU Bo)
freeCodeCamp (A)
eT oko emir neem melee tele
3
g
é
m
&
sau.ans LHOT
Diagram of a binary search tree
Let's us look at the relationship between
the nodes.
¢ A isthe root node.
e The left subtree begins at B while
the right subtree begins at c.
¢ Node A has two child nodes - B
and c.
e Node ¢ isthe parent node to F
and G. F and G aresiblings.
¢ Node F and G are knowas leaf
nodes because they do not have
—children
© scanned with OKEN ScannerPee
freeCodeCamp (A)
TU Keele team ice} Pee ate ena)
nodes because they do not have
children.
e Node B isthe parent node to D
and E.
¢ Node p is the parent node to
and 1.
* D and € aresiblings as wellas H
and 1.
¢ Node E isaleaf node.
So here are some important terms that we
just used to describe the tree above:
Root: The topmost node in the tree.
Parent: A node with a child or children.
Child: A node extended from another node
(parent node).
Leaf: A node without a child.
© scanned with OKEN ScannerConstruct Compl... e
Gu eta en
Construct Complete Binary Tree from its
Linked List Representation
Given Linked List Representation of Complete
Binary Tree, construct the Binary tree. A complete
binary tree can be represented in an array in the
following approach.
If the root node is stored at index i, its left, and
tight children are stored at indices 2*i+1, and
2*i+2 respectively.
Suppose a tree is represented by a linked list in
the same way, how do we convert this into a
normally linked representation of a binary tree
where every node has data, left and right
pointers? In the linked list representation, we
cannot directly access the children of the current
node unless we traverse the list.
The above linked list represents following binary tree
©)
@) G5)
Qe &
Open In App
© scanned with OKEN ScannerRecommended Practice
Make Binary Tree From Linked List
Irytt
We are mainly given level order traversal in
sequential access form. We know head of linked
list is always is root of the tree. We take the first
node as root and we also know that the next two
nodes are left and right children of root. So we
know partial Binary Tree. The idea is to do Level
order traversal of the partially built Binary Tree
using queue and traverse the linked list at the
same time. At every step, we take the parent
node from queue, make next two nodes of linked
list as children of the parent node, and enqueue
the next two nodes to queue.
1. Create an empty queue.
2. Make the first node of the list as root, and
enqueue it to the queue.
3. Until we reach the end of the list, do the
following.
a. Dequeue one node from the queue. This is
the current parent.
b. Traverse two nodes in the list, add them as
children of the current parent.
cc. Enqueue the two nodes into the queue.
Open In App
© scanned with OKEN Scanner10:40 BRIG
Construct Compl...
Pas bd From ge
Pee et
pus ac,
push(&head, 30);
push(&head, 25
push(&head, 15);
push(&head, 12);
push(&head, 10); /* First node
BinaryTreeNode *root;
convertList2Binary(head, root)
cout << "Inorder Traversal of
inorderTraversal(root);
return 0;
Output
Inorder Traversal of the constructed Binary
25 12 30 10 36 15
Time Complexity: O(n), where n is the number of
nodes.
Auxiliary Space: O(b), Here b is the maximum
number of nodes at any level.
This article is compiled by Ravi Chandra
Enaganti.
Cyt Ne) +)
© scanned with OKEN ScannerExternal Sorting Algorithm
Certainly! Let's explore the array and linked list
ieee e le Ue
1. Array Representation:
In an array representation, we store the
UCT -MaTolol A TAE-LEEN A
If the root node is stored at index i , its
left child is stored at index 2*i + 1, and
its right child is stored at index 2*i + 2.
SUE) ceo LCR RR Cd
binary trees (where all levels are
completely filled except possibly the last
AID}
Pee ORR acne ih
UMBC em RISE)
UTE iie UC aR Ole R UT RC TM tele Oe
Each node contains data and [tele Co)
LM igeaek- eMac eenni te] (if they exist).
Mana ei Cos ent]
CerT AMA Uae MULT a PTW AUK}
CEES) oclug) binary tree and its
WS TCS ete aos
ey Sur Uliale a
© scanned with OKEN ScannerExternal Sorting Algorithm
iro) eLL SS
« Array Representation:
arr = [A, B, C, D, E, F, G]
Oe Beas elt
Each node contains data and pointers to
its left and right children.
In summary, both representations have their
advantages and use cases. Array representation
is more efficient for complete binary trees, while
linked list representation handles arbitrary binary
I-11 eo SLC
1 eee ee CL
2 [BB tutorialspoint.com | +3 more
ones Oa)
(2 { What is the difference between a complete binary tr4
ey Ask me anything...
© scanned with OKEN ScannerExternal Sorting Algorithm
DVN ast -t-1 ce toto
OM enV Acc Rt Glen Ciel TET
TENS Le Rt) eRe la oieliPccl ORO LaLa
Bren)
* In an m-way tree of order m , each node can
CefoTal eT to) CHL LA]
mee Leela
* The goal of an m-way search tree is to
minimize the number of accesses
(comparisons) for insertions, deletions, and
aS
* The height of an m-way search tree of height
MRSC LUMO me) [ee oe)
close to O(h) .
Structure of an m-Way Node:
« Anode in an m-way search tree has the
following structure:
struct node {
Stee Las NTS
SLO
struct node* child[MAX + 1
Ask me anything...
© scanned with OKEN ScannerExternal Sorting Algorithm
struct node* child[MAX + 1];
NaS F eK: Me Toeiaye
Cofol Tah) 9 Cn Maal bg o-oo) (el -Ta)
that a particular node has.
BUR I Role Mnele Me ole CoRR
Clit) Mn ee
The addresses of child nodes are stored in
LUTE Lc Nye Ke
MAX. signifies the maximum number of
values that a particular node can contain.
Searching in an m-Way Search
ancl
* Searching for a key in an ae Aor toes
STI TREC eR EM RAST RecN
* To search for a value val :
SPEC ladle oar
en Me PMR Re era tots eS
ACL oe
SAAR OMe ACCOR UCU R Relat SEI
Move to the left child.
ey Sur alee
© scanned with OKEN ScannerExternal Sorting Algorithm
PMs laU mR mo ne Relea
node is reached.
Example:
* Consider a 5-Way search tree shown belgw:
iT
a
44 80 100
aan
a Pa)
* To search for 77:
Start at the root ( 76 ).
Move to the fourth sub-tree (since 77 >
eee y
Tamara cerel a ole (Mel MUCOUS oC
< 80 ,so move to the first sub-tree.
Since 77 is available in the only node of
USE em Le ere corde]
Implementation:
* The search function recursively searches
Sle R LY RR UR
y Ask me anything...
© scanned with OKEN ScannerExternal Sorting Algorithm
SOURCE TOR Ree TITOT ane TOORCOT CORE
Cree
In the root node of the fourth sub-tree, 77
< 80 ,so move to the first sub-tree.
EST Teta ORCI Le) Mn NVM Eee (olf
UTESSI0 omc tom Ua -etcKeSeTe (cero 0]
Implementation:
¢ The search function recursively searches
LOEB RRs
CM Met ened ae Co ee R Le)
value exists in a specific node
In summary, multiway search trees generalize
binary search trees, allowing each node to have
multiple children. They optimize search
operations while maintaining a balanced
FS) (ft (0300. ae
Pee eee eka
ae ecko ea
Areca ere
(D { Whats the difference between a binary search treq
ey Ask me anything... () d
© scanned with OKEN Scanner= SScholarHat 8
By DotNetTricks
What is an AVL Tree in
Data Structures?
AVL tree in data structures is a popular self-
balancing binary search tree where the
difference between the heights of left and right
subtrees for any node does not exceed unity. It
was introduced by Georgy Adelson-Velsky and
Evgenii Landis in 1962, hence the name AVL. It
automatically adjusts its structure to maintain
the minimum possible height after any operation
with the help of a balance factor for each node.
Balance Factor in AVL Tree in
Data Structures
The balance factor of a node in an AVL Tree is a
numerical value that represents the difference in
height between the left and right subtrees of that
node. It is the extra information used to
determine the tree's balance. The balance factor
is calculated as follows:
height(left subtree) -
[intl = Intra
balance factor of a given nod
LU) ooe Taine eS mer we
© scanned with OKEN Scanner= SScholarHat 8
By DotNetTricks
Is aes as TOllOWS.
height(left subtree) -
inl = Ine,
balance factor of a given nod
The value of the balance factor always lies
between -1 and 1.
edit aL = Inti
1. If the balance factor of any node = 1, the left
sub-tree is one level higher than the right sub-
tree i.e. the given node is left-heavy.
2. If the balance factor of any node = 0, the left
sub-tree and right sub-tree are of equal
height.
For leaf nodes, the balance factor is 0 as they
do not contain any subtrees.
3. If the balance factor of any node = -1, the left
sub-tree is one level lower than the right sub-
tree i.e. the given node is right-heavy.
Hence, in this way, the self-balancing property of
an AVL tree is maintained by the balance factor.
Thus, we can find an unbalanced node in the tree
Upcoming Master Classes
© scanned with OKEN Scanner= SScholarHat =
By DotNet Tricks
Hence, in this way, the self-balancing property of
an AVL tree is maintained by the balance factor.
Thus, we can find an unbalanced node in the tree
and locate where the height-affecting operation
was performed that caused the imbalance of the
tree.
seca Avltree
AVL Tree Rotations
AVL tree rotation is a fundamental operation
used in self-balancing binary search trees,
specifically in AVL trees. Due to any operations
Upcoming Master Classes
© scanned with OKEN Scanner= SScholarHat B
AVL Tree Rotations
AVL tree rotation is a fundamental operation
used in self-balancing binary search trees,
specifically in AVL trees. Due to any operations
like insertion or deletion, if any node of an AVL
tree becomes unbalanced, specific tree rotations
are performed to restore the balance.
The tree rotations involve rearranging the tree
structure without changing the order of
elements. The positions of the nodes of a
subtree are interchanged. There are four types of
AVL rotations:
Rotations
Gel co nue cy
Right Left ea
Rotation Rotation
Upcoming Master Classes
© scanned with OKEN Scanner= =
= SScholarHat 8
By DotNetTricks
Cry
Pucca) Seo)
ey
oe
aa
ior
(RL Rotation) [RR Rotation) {LL Rotation)
Sschlata
1. Left Rotation (LL Rotation)
In a left rotation, a node's right child becomes the
new root, while the original node becomes the
left child of the new root. The new root's left child
becomes the original node's right child.
Upcoming Master Classes
© scanned with OKEN Scanner= =~
= SScholarHat =
By DotNetTricks
Ina left rotation, a node's right child becomes the
new root, while the original node becomes the
left child of the new root. The new root's left child
becomes the original node's right child.
1
4% 4
| §
0 0
«0
2. Right Rotation (RR Rotation)
In aright rotation, a node's left child becomes the
new root, while the original node becomes the
tight child of the new root. The new root's right
child becomes the original node's left child.
AD setlarit
2 A
Upcoming Master Classes
© scanned with OKEN Scanner=
= SScholarHat 6
By DotNetTricks
3. Left-Right Rotation (LR
Rotation)
An LR rotation is a combination of a left rotation
followed by a right rotation. It is performed when
the left subtree of a node is unbalanced to the
right, and the right subtree of the left child of that
node is unbalanced to the left.
Upcoming Master Classes we
© scanned with OKEN Scanneran
Seats 8
By DotNetTricks
tt
4. Right-Left Rotation (RL
Rotation)
& ScholarHat
An RL rotation is a combination of a right
rotation followed by a left rotation. It is
performed when the right subtree of a node is
unbalanced to the left, and the left subtree of the
right child of that node is unbalanced to the right.
sir
Upcoming Master Classes
© scanned with OKEN Scanner‘fo Schoathet
Read More - Data Structure Interview Questions
for Experienced
Standard Operations on
AVL Trees in Data
Structures
1. Insertion: A newNode is always inserted as a
leaf node with a balance factor equal to 0.
After each insertion, the ancestors of the
newly inserted node are examined because
the insertion only affects their heights,
potentially inducing an imbalance. This
process of traversing the ancestors to find
Upcoming Master Classes
© scanned with OKEN Scanner=~
= @ScholarHat
By DotNetTricks
. Insertion: A newNode is always inserted as a
leaf node with a balance factor equal to 0.
After each insertion, the ancestors of the
newly inserted node are examined because
the insertion only affects their heights,
potentially inducing an imbalance. This
process of traversing the ancestors to find
the unbalanced node is called retracing.
Algorithm for Insertion in an AVL Tree
Byes
Fae eg a MCC MES aT
: Calculate and check the bala
: If the balance factor follow:
: Else, perform tree rotations
: END
Let's understand with an example
1. Let the initial tree be:
Upcoming Master Classes
© scanned with OKEN Scanner= SScholarHat B
By DotNetTricks
1. Let the initial tree be:
Initial tree for insertion
SScholartat
Let the node to be inserted be:
New node
2. Go to the appropriate leaf node to insert
Upcoming Master Classes
© scanned with OKEN ScannerScholarHat B
—_— By DotNetTricks
2. Go to the appropriate leaf node to insert
a newNode using the following recursive
steps. Compare newkey with rootKey of
the current tree.
1.If mewKey < rootKey, call the
insertion algorithm on the left subtree
of the current node until the leaf node
is reached.
2. Else if newkey > rootKey, call the
insertion algorithm on the right
subtree of the current node until the
leaf node is reached.
3. Else, return leafNode
Finding the location to
insert new node
SSeholarHat
3.Compare leafKey obtained from the
Upcoming Master Classes
© scanned with OKEN Scanner= SScholarHat B
By DotNetTricks
3.Compare leafKey obtained from the
above steps with newKey:
1. If newKey < leafKey, make newNode
as the lef tChild of leafNode.
2. Else, make newNode as rightChild of
leafNode.
0-0 @
0
‘S scholartit Inserting the new node
4. Update balanceFactor of the nodes.
Upcoming Master Classes
© scanned with OKEN ScannerScholarHat B
~_ By DotNetTricks
4. Update balanceFactor of the nodes.
Updating the balance factor after insertion
SScholartiat
5.If the nodes are unbalanced, then
rebalance the node.
1. If balanceFactor > 1, which means
the height of the left subtree is
greater than that of the right subtree.
So, do a right rotation or left-right
rotation
1.1f newNodeKkey < leftChildKey
do the right rotation.
Upcoming Master Classes
© scanned with OKEN ScannerScholarHat B
By DotNetTricks
1. If newNodeKey < leftChildKey
do the right rotation.
2. Else, do left-right rotation.
1 1
Bean th rei otaton
Upcoming Master Classes
© scanned with OKEN ScannerScholarHat B
By DotNetTricks
alan thee with faton
Sit
2. If balanceFactor < -1, it means the
height of the right subtree is greater
than that of the left subtree. So, doa
right rotation or right-left rotation
1. If newNodeKey > rightChildKey
do a left rotation.
2. Else, do right-left rotation
6. The final tree is:
Upcoming Master Classes
© scanned with OKEN ScannerScholarHat B
By DotNetTricks
seat Final balanced tee
2. Deletion:A node is always deleted as a leaf
node. After deleting a node, the balance
factors of the nodes get changed. To
rebalance the balance factor, suitable
rotations are performed.
Algorithm for Deletion in an AVL Tree
& Sydaleay
: Find the node in the tree. If
: Delete the node using BST de
: Calculate and check the bala
Upcoming Master Classes we
© scanned with OKEN Scanneree oka bi 2 See ad
=a
= SScholarHat 8
By DotNetTricks
Algorithm for Deletion in an AVL Tree
: START
: Find the node in the tree. If
: Delete the node using BST de
: Calculate and check the bala
: If the balance factor followg
: Else, perform tree rotations
: END
Let's understand with an example
1. Locate nodeToBeDeleted (recursion is
used to find nodeToBeDeleted in the
code used below).
Node to be
Upcoming Master Classes
© scanned with OKEN ScannerScholarHat B
By DotNetTricks
Ota
‘Soviet Locating the node to be deleted
2. There are three cases for deleting a node:
1. If nodeToBeDeleted is the leaf node
(ie. does not have any child), then
remove nodeToBeDeleted.
2.If nodeToBeDeleted has one child,
then substitute the contents of
nodeToBeDeleted with that of the
child. Remove the child.
3.If | nodeToBeDeleted have two
children, find the in-order successor w
of nodeToBeDeleted (ie. node with a
minimum value of key in the right
subtree).
Upcoming Master Classes
© scanned with OKEN ScannerTe
dea
=
= =~
= SScholarHat =
By DotNetTricks
‘Sia Frag bese
= Substitute the contents of
nodeToBeDe leted with that of w.
1
Sis te otto 9
tenet » i Ne
with that fw
LU fofefey priate ERC eC}
© scanned with OKEN ScannerScholarHat B
bal By DotNetTricks
= Remove the leaf node w.
removed
/\
— Fee
3. Update balanceFactor of the nodes.
1
Calculate bF Q
Upcoming Master Classes
© scanned with OKEN ScannerScholarHat B
By DotNetTricks
Sica Update bf
4. Rebalance the tree if the balance factor
of any of the nodes is not equal to -1, 0, or
1.
1. If balanceFactor of currentNode >
1,
1.If balanceFactor of leftChild
>= 0, do right rotation.
Upcoming Master Classes
© scanned with OKEN Scanner= =~
= SScholarHat 8B
By DotNetTricks
seine bein ee
2. Else do left-right rotation.
2.If balanceFactor of currentNode <
-1,
1.If balanceFactor of rightChild
<= 0, do left rotation.
2. Else do right-left rotation.
5. The final tree is:
sade AVL final tee
Implementation of AVL
Tree in Different
Upcoming Master Classes Me
© scanned with OKEN Scanner= =~
= SScholarHat B
By DotNet Tricks
Complexity Analysis of
AVL Tree Operations
1. Time Complexity:
Operations Best Average Worst
Case Case Case
Insertion 0 (log 0 (log |. log
n) n) n)
Deletion | (1og|0 (log |0 (log
n) n) n)
Traversal on) |o cn) 0 (n)
Search
0 (log oO (log 0 (log
n) n) n)
2. Space Complexity: Space complexity is the
same as that of Binary Search Trees i.e., 0(n)
as AVL Trees don't modify the data itself.
Applications of AVL Trees
Upcoming Master Classes Me
© scanned with OKEN Scanner= SScholarHat B
By DotNetTricks
1. It is used to index huge records in a database
and also search in that efficiently.
2.For all types of in-memory collections,
including sets and dictionaries, AVL Trees are
used.
3. Database applications, where insertions and
deletions are less common but frequent data
lookups are necessary.
4. Software that needs optimized search.
5. It is applied in corporate areas and storyline
games.
Advantages of AVL Trees
1. AVL trees are capable of self-balancing.
2. It cannot be skewed.
3. Compared to Red-Black Trees, it offers faster
lookups
4. Superior searching efficiency compared to
other trees, such as the binary tree.
5. Height is limited to log(n), where n is the
number of nodes in the tree as a whole.
Disadvantages of AVL
Trees
1. Implementing it is challenging.
Upcoming Master Classes
© scanned with OKEN Scanner= SScholarHat B
By DotNetTricks
1. Implementing it is challenging.
2.Certain procedures have high constant
factors.
3. Compared to Red-Black trees, AVL trees are
less common.
4. As additional rotations are conducted, AVL
trees offer complex insertion and removal
procedures because of their rather rigid
balance.
5. Requires to process more for balancing.
Summary
AVL Trees are a great tool to help structure and
organize data. By keeping track of the difference
in heights between two nodes, AVL trees can
save you from calculating these values
manually. Furthermore, as it is self-balancing,
you need not worry about the tree becoming
unbalanced as it grows. While traversing may
take longer due to all the re-balancing, this
method gives you greater control over your data
sets than many regular BSTs. To implement your
theoretical knowledge about AVL Trees, consider
our Data Structures and Algorithms
Programming Course.
Upcoming Master Classes
© scanned with OKEN Scanner10:50 OG Fi + OG rem al 31%
Shield® Level Annuities : x
Ad - A Level Of Protection, Growth Opp.
RED-NLACK TREE
Ancrodacti
At blck tee ba kind of veftulncing binary search wee where each node hs a exis bi
uid that bi ofeniterpeted a the color (ed or black), Thee colors ate wd o ensue that
the tre remains balan ding isertions and dktions.Akhough the balince of the tse &
ot pest. This re was invent in 1972 by Rolf Baye.
Rules That Every Red-Black Tree Follows:
[Every node basco ether red or bck
“Tre root of thee aways Hack
‘Tere ae no two ajacemt ed nodes (A sed node canno havea red pret orci).
Every path fom anode Gclaing oa) w ay as descendants NULL nodes hs the
samme uber of black cle.
'. Alla nades ae black nes,
EXAMPLE
Pare Ten
winese A TES AN
The above rea Red lack re where every messing all the properties of
Red-Black Tree.
Why Red lack Trees?
Most ofthe BST operations. such. ma. min. inset, delete ec) ake OX time where hs
the eight ofthe BST. The cont of thee operations nay hecomn Ota) fora skewed Binary tee
It we make sre tat the eight ofthe te rim Obs) aller every insertion an deletion,
‘then we can guaran an upper Bound of tg n oral these operations. The eight ofa Red
Black wee always Olosn) whee is the mmber of nodes in the te. Where "a" the atl
‘numberof elements inthe red-blak ire
Comparison with AVL Tree
‘The AVL tees are more balanced compared to Re-Black Tres, bit they may couse me
routings dung insertion and deletion involes aque inetons and
‘elton, then Red-Black recs should ‘meron al deetions are ss
freien and search ea more fequene © should be preted over Red
Black Tee
Ineresting pnts about Red-Black Tree:
Black height of he reblick ee i the mmr of ack px on pth fom he rot
© scanned with OKEN Scanner10:50 @ GR * OG mem al 31%
Shield® Level Annuities : x
Ad - A Level Of Protection, Growth Opp..
‘ost othe Ht operations eg SEAR AN, HN NEE, ERE ake UR) te EEE
the height ofthe BST. The cost ofthese operations may become O(a fora skewed Binary we,
‘ve mae sue tat tbe height of the we remains OXog) aller every inserts deletion,
then we can guarantee an upper baud of (kg) fra ese operations. The begh of Red
‘Black. ee i always Odo 0) whe nis the numberof woes ia the te. Whese a” the
tnamber of elements inthe red-black tee.
‘Comparison with AVL Tree:
‘The AVL tres ae more talanced compared to Red-Blik Tress, ba they may’ case more
‘rotations during insertion and deletion. So if your application involves fequent insertions and
eketions, then Re Blick trees soul be prefered. And ifthe insertions and deletions are est
frequent and seach i a more frequent operation. then AVIL tee shoul be prefered over Re
Bek Tee
Interesting points about Red-Black Tree:
1. Block height of he sec tee the mumber of ack mae on pth om the st
ane to al node. Lea pes are alo counted black noes So, reblck re of
‘hth lack ig == h2.
Height of rethlck tse with 9 nades i he= 2 Inn
3. Alleaes (NIL) ae beh,
44 Te bck depth of oe is define the numberof ack odes fom the roe to that
ave ie the numberof Mack ancestor.
S. Eryrodback ue is aspecial case ofa inary we
ack Height of Red-Black Tree
Black eights the mer of Mack mies om ath Fm the
‘counted Mack nds. From the above properis 3 and 4, we can derive, a Red-Black Tree of
"ight has blac >= W2
[NOTE: Every Red lack Tres with n nodes has height <= 2Logsinet)
‘The folowing operations ae performed oa Red/Black Tree
1. Search
2 tnerion
3. Deletion
‘Search operation in Red-Black Tree
Every r-black te a apoi case ofa binary tre so the searching algo of re-lack
toe silat that of inary te,
sample: Searching 1 in the fllowingred-black tree.
CTai}
ny
© scanned with OKEN Scanner10:50 © GF * OG te all ST%
Shield® Level Annuities
Ad + A Level Of Protection, Growth Opp. .
x
DG =
Solution:
1. Strt fom the
2 Compare the inserting ckment wih rot, if ens than son, then rears for Ket, ee
reune for righ
3. be elemento search is found anys, eur re, le rene
«
soa e
Insertion operation in Red-Black Tree
Inthe RedeBlck tise, we we two too od the buining.
1. Recoloring|
2. Rotation
Recoloring isthe change in color ofthe nee i, if is ed then change ito back and vce
‘sera [Cust be noted hi the color ofthe NULL node i always black, Morsver, we alays
try re-coloing fir ifre-cooring doesnt work, hen we go fr ration
Following is ad
color of he unc
ld algortn. The algorithms have manly evo cases depening upon the
cle meats new rie pret sibling) Ifthe wcll, we do eco It he
Uncle isblck, we dy rotations andor recooring
Laie
Fes, you ne ost he me MORAG ad asin ted ort
Now. te nde aot ten bot tise bck he lor
ofthe parent nods I cole ack then dont change he color Bu ii ot Le. fed hen
shock the color of the nodes ele. I the node's uncle hs ed cor the change the ols of
‘he nodes parent and uncle fo blek and that of grandfather to red color and repeat the same
© scanned with OKEN Scanner10:50 {) BE Ga ¢ OG tee ul s1%e
Shield® Level Annuities :
Ad + A Level Of Protection, Growth Opp. .
x
Following i «desi! algorithm. The algorithms have mainly two cass depending upon he
col ofthe uncleUncle eas ew pode para sing). Hthe alee ed, we do roscoe the
Logie:
Fist you fave to inert the node similarly 0 that ina inary tre al assign a re color 19
Now, ifthe pode isa root mode then change its color Black, bat iit ot hen check the olor
ff the pare! node Ia cole lack them don't hangs the colors not hen
sec the color ofthe node's uel. I the nade's uncle is ed coer then change the eal of
‘he node's parent ad inte to blck and that of grandfather to re color and rept the same
process for him ..grandfathen)
Algorithm
|. Perform standard BST incerton and make the sob of newly insert nds a8 RED.
2. mew aoe (x) isthe roo, change the cole of «as BLACK.
5. Dore follwing ifthe color of new node (x°s) parent at BLACK and x not the
4) HP's nleUnele means new poe paren sibling) is RED (Grandparent must
have been black from Red Black Tree Property)
> Change ie colour of parent and uncles BLACK.
> Colourof a grandparent a RED.
> Change x= 1's grandparent, repeat tps 2a 3 for new
1). Ux uncle is BLACK, then there can be four configurations for x x's prea (p)
and x's grandparet(g)
2 Left Lot Case (pi et cil of gan child fp)
Left Right Case (pis ef cil of gad xs the ig chil fp)
> Right Right Case
Rit Let Case
+ Lett ght Case (LR rotation)
© scanned with OKEN Scanner10:30 Of) Ge OG tem al 31%
Shield® Level Annuities : x
Ad - A Level Of Protection, Growth Opp.
An AX:
BWA
eate eRe lack Tee withthe flowing sequence of rmbers8.185,151725 0 en
is Empty. So insert newNode as Root node with black color
insert a8) cee)
“Tree is not Empty. Se sash rea coter.
=
© scanned with OKEN Scanner10:50 BW G+ OG tee all 31%
Shield® Level Annuities
Ad - A Level Of Protection, Growth Opp.
x
umber 8.185,5,17,25,0 ona 80
Tree is not Empty. So insert newNode with red color.
oo
Aer Resor pin. cs stn a Re Bask Te
© scanned with OKEN Scanner1050 BW & + OG ral 31%
Shield® Level Annuities
Ad - A Level Of Protection, Growth Opp.
x
proms)
© scanned with OKEN Scanner10:50 BY) GH * OG re ul ste
Shield® Level Annuities
Ad. A Level Of Protection, Growth Opp. x
© scanned with OKEN Scanner10:50 BW G+ OG tee all 31%
Shield® Level Annuities : x
Ad A Level Of Protection, Growth Opp. .
Deletion in Red Black Tree
‘The blow table's seul to tenty the cave adits corressonding et of action tobe performed when
cetngs noe tom Re lek Tee
zample 1: Delete 30 rom the RB ween. 3
eC ai)
eo
‘outratnave to etch or 30, once found pertrm BST ceeton. Fora node whale "30, nether
© scanned with OKEN ScannerO51 OSs OG rm al 31%
Shield® Level Annuities : x
Ad A Level Of Protection, Growth Opp.
‘ample: Delete 30 fromthe RB tee in ig3
eo
= Ld
eooso oe
eo
‘Your have och or 30, onc foun perform ST deletion. Fora nde withvalve 0; Father
te maemum af he ft subuee ora minum othe right sub ard vepace 30 with tat ae Tas
ar
~~
eoco
©
a Trae ater epicing 20 wth min erent amine etree
‘oto tnetabesbove and youllobseve cate sstfied by th te,
-Aerremovire te redles vate F
‘sere tat you perform covet actions, thee wisi hl athe properties ofthe we.
trample 2:Oelte 15 fom below Rr ©
ott RB Tree ®
°
© scanned with OKEN ScannerO51 ONG OG rem al 31%
Shield® Level Annuities
Ad + A Level Of Protection, Growth Opp.
x
trample 2: Delete 5 rombelow Ree
ebook (ale) an cases perfec
trample: elt 5" fom MBA
(Ant RB Te, (8) RL no aan place of 35
Delete rade with vale we, replace with 8 erode a shown. Now,
andsiing's bth eden areas bac (ogee aden ML nodes, satis a
‘canstone fae 3 Hee,
© scanned with OKEN ScannerO51 BW + OG em ull 31%
Shield® Level Annuities
Ad - A Level Of Protection, Growth Opp.
x
Ct)
apne ee aera sapped
2. De prentis20,
23. patssbingis30
20 necomes 08 ard hence the problem nt ese yt. Realy ease 3
“The resuting tee look the onan the above
ig. Tee afer a3 sapped
Fg: ML Node removed after aplnng ations
Founsit'scase2, the sialest ofa
‘The rootreved 08 and becomes Mack node. And you'redone deleting 5 sce
Example: Delete 1 trom below (8.
© scanned with OKEN Scanner1051 BW ¢ OG Fal 31%
Shield® Level Annuities
Ad A Level Of Protection, Growth Opp.
x
(At 8 Tee) ML ode aden place 015
sown ne 13(8,
De sting em. Cent, ates ppb
Ro Tree ater cate sapped
(a) wap D's parent’ clr with ili’ cr. hrow hs confining but ae ey and hep
Fotoning, Te ree ok he 14
(o)Perermrotaion at paren node in teton of 8. The ree Boome ke te one nf 35 DBs
su ere wats problem).
(6 Apply cae 2 aed andthe RB ee fe fromthe D8 ode a shown ni 36
pow t's tresome, bt swear you pate these eamsles 2-3 times, you wit have egoadarasp of
© scanned with OKEN ScannerSIT OM oe OG rer ul 31%
Shield® Level Annuities
Ad + A Level Of Protection, Growth Opp.
x
IL Node emesis sling ations
(2) Arply cane a erlaied and he RB
‘is resame, bu smear you practice nee examples 2-2 ie, you wi ve a ocd grasp of
the concept of dition inh trees.
oo
oe e.
ea £6
@©e005 0@ @Oo
co eo
(Ait Re Tee, (8 ML nde edn pace of
‘Shin ig 1718) Check forthe cases which tthe caren tee andi’ case HOB big itr).
Ro Tee aera is oppad
Scare for cass that an be appli andcase 5 seems it here a se 3)
(ar eee ater swapping colors of 30 258) re ater otaton
cates appiee a folowe
(a) wap color of noes 30a 25 190)
(0 Reta ing node nthe reson pian ode ene sero gh retaon a
Tne doutecnoehs PARORASEM 220wpeot e ande
farce onal re
° e
© scanned with OKEN Scanner10:52 OWS OG em al 31%
Shield® Level Annuities : x
Ad - A Level Of Protection, Growth Opp. :
(a) Tee ater sping olor 308 258) Tee ar rotaton
(o) swap color of odes 30 2n625 391A)
(2) Rott at ing noe intercon oppo to he D8 node. Hees, ptr eet rotation st
sade 20 snd te ree becomes he. 19()
‘hn tat ate (on fal for case) seams
‘opty cae soon
(0) swap color of 08 parent with O's bing
(2 Peta rotation t parent node inthe section 8 208)
Ii Node removes ster apg ations
(c)orange 08 noe to lace nase, Ato, change te clo of ings trestle andthe
‘ia Be wt ok i 2
‘And, The Bre tree af element 1 aswel at of any coube nse.
Spay Tree
Spay wees ae the self atancing self adjusted bnay search wees, Inoer wor, we em say
‘thar the spay tres are the varan’ of he binary search ees. The prerequisite fo he splay tees
that we shook! Know about the Binary search res.
AAs we already know, the time complesay of a binary search tse in exery case. The tine
‘compleiy ofa binary search tein the average ease OMagn) andthe ine complet ia the
‘worst sie is On), In binary’ seach te, the we ofthe left street the rot
nde, and the value ofthe right subtree is greater than the root node in such case, the tine
complexity would be Odlgn) Ite brary te is Heft skewed or right skewed, tben the time
‘complexity woul be Ola To limit the shewoes, the AVL ad Red-Black re eae ato the
pictur, ving Oflogn tne complerty fr all te operations in all the cases, We ean also
Inprove ths tine compleiy by do
tore practical implementation, x9 the mew Tree data
© scanned with OKEN Scanner10:52 OWS OG rm al 31%
Shield® Level Annuities
Ad - A Level Of Protection, Growth Opp.
tee
Splay Tree
Sky tres are the sl blancing or selFajoted binary search wes Inher words, We can ty
that the splay wees ae the varias of he bay search wees. The preeyuisite for the play ces
that we should know about the inary serch eres.
[As we already Know, the time complexity of binary search tee in every ease, The tne
comple ofa binary sare ue in the average ease i Ogg) andthe ne complet ia he
‘wort cise is Orn), Ina iar serch te, te ave ofthe Je sare sale than the rot
ode, and the vale of the eight subtree is greater tan he root node; in such ease, the tine
complexity soul be Odlgn). fhe binary tre is lefskewed or right-akewed, them he time
complexity would be Of) To lini the skewness, the AVL at! Red-lck tee came ito the
Picture, having Olan tne eompesty for all the operations in all the cases, We can abo
Improve this time complenty by doing mone poetical implementations, 0 the new Tre data
structure was designed. kaown a a Spi woe
Wha in Spay Tre?
Asply toe iva setulncing toe, bt AVL and Red-Blak tres ar ao sean tres
then. What rakes he splay tee uni wo tes sone exis propery tat kes nique
‘ssplaying
A splay uce contains th same operations as 4 Binary scurch ee, ie Isertion, deletion and
searching, butt ao contains one more operon. i slaying, So. all the operations in the
play re ar followed by paying
Sly esate not sry alco ess, tt they are rw balancod toss, Lets derstand
the search operation the spite
‘oppose we want to search 7 element inthe ee, which i shown blow
To sarch any element in the splay re, frst, we will perform the standand binary Search te
‘operation. As 7 i Tes than TI) <0 we wl com Yo the kof the rot oe. Afer performing he
Starch opention, we need to perform slaying. Hee spaying means that the operation that we are
performing on any clement shook! Race the roo ne fer pertorming some errangerments. The
Fearangemnt of thetic wil he done though the ations.
Note: The splay wee came defined as the seas ee n which any operation performed
(on the element would rearrange the tee 30 tha he
reo the ve
feet on which eperaton a beet
Ina splay tos every operation i performed at the rox ofthe re, A the ope
luce te iavined witha eomon operation calle "Splayag™
Splaying an element is the proces of begin ito the root poston by perfor
suitable tation operations,
Ina splay te, slaying an clement earanges llth element inthe te tat splayed element
{speed atthe rot ofthe ee
By spaying elements we bring wore Gqueily ed elements cher to the rot ofthe tee so
that any operation on those ckments perform quickly. That means the spying operation
auomatically brings more Je chser to the root of the tre
Every opention on splay tre peation. For example, the insertion
operation fr imsers the nw elemenig Tae Pay search ee insertion proces, them the
‘sowlyiserted emo is paye 0tha it placed atthe rot of the oe. The Search operation
ing splay te is othing but searching te clement wing inary search process and then spying
© scanned with OKEN Scanner10:52 OWS OG rem al 31%
Shield® Level Annuities
Ad A Level Of Protection, Growth Opp.
tee
In splay te, every operation is perform atthe root ofthe tse. A he operations in splay
tise re involed witha common operation called! "Spaying"
he proces bringing i to the rot position by performing
Ina splay te, spaying am cla earanges all the elements inthe tre otha played element
Is placed ar the roto the tes
‘By spaying elements we bring move fequeny wed elements closer to the oot ofthe tee 50
thet any operation on thos elements i perfoted qucly. That means the spaying operation
suomatically twigs more tquenly used lemens closer 10 the mot of the wee.
Every operation on splay tee performs the splayng operation. For example. the iaserton
operation fist nse the new element using the Day Search tee imertion proces. then the
newly inserted element i splayed otha it splice a the oot ofthe wee. The search operation
‘na splay te is mothing bt searching the clmene wing nay search process a then spaying
that seared cheat so that it i peed at the root of the te,
In py te, spay any clement ease the following rotation operations
‘Rotations in Splay Tree
1.Zig Rotation
2 Zag Rotation
23. ig Zig Rotation
44 Zan Zag Rotation
5. Zig-Zag Rotation
(6 Za Zig Rotation
Example
Zig Rotation
“The Zig Rotation in ply resi to the single righ rotation in AVL Tee rations. I ig
rottion, every me tes one postion tothe right from is cuentposion. Conse the
following example.
Splay (3)
Zig Rotation
‘Zag Rotation
“The Zag Rotation in splay rei smile othe single ef
rattion, every node moves one poston tothe kt fon
tion i AVL Tre cations. 48
is curent postion, Consider the
splay (5)
Dig-Fig Rotation
© scanned with OKEN Scanner10:52 OWS OG em al 31%
Shield® Level Annuities
Ad A Level Of Protection, Growth Opp.
6s 28 6 »d
x
Zag Rotation
The Zag Rotation in splay tc is siniar to the single let rottion in AVL Tice rotation, I ag
rotion, every node moves one postion tothe let from ke cure’ postion. Consider the
folowing exam
splay (5)
Rotation
ig: Rotation
‘The Zig-Zig Rotation in spay ice isa double zig ctaion. In gig rotation, every noe
roves two postions to the ight fom cute poston, Coser the following example.
Q
Q ©
6 & cs
Splay (2)
ig-Zig Rotation
‘ag-Zag Rotation
The Zag-Zag. Rotation in spy ice is double 2g rotation. In zag-zag rotation, every node
moves to postions he let om ts cent postion. Conse the following example
Splay (6)
Zag-2ag Rotation
© ceuieren sae
Zig-Zag Rotation
The Zig-Zag Rotation in splay eo sa sequence of ig otto followed by 2ag rotation In ig
24g rotation every node moves ane postion w the rg followed by one postion othe et om.
ts current poston. Conse the following example
splay (4) 56 of 76
©
© scanned with OKEN Scanner10:52 OWS OG rm al 31%
Shield® Level Annuities
Ad - A Level Of Protection, Growth Opp.
tee
Zig-Zag Rotation
The Zin-Zag Rotation in phy te sequen ofr rttion flow by 2 tain
itcrrem positon, Consider he following example
Splay (4)
a Q
®@ &
S &”
‘Zag-Zig Rotation
Splay (4)
‘The Zag-Zig Rotation ia spay wee isa sequence of zag statin followed by zig oti. ta
233-2 rtlion, every modo moves one psi othe followed by one postion the gh
from fs cure positon, Consider he following example.
‘Rataions
‘the
six types of
tations used for spaying:
2g tation (Right tation)
2a wai (Let station)
“Zig mig follow by 248)
Zag 2ig (Zag flowed by 2)
Zig vig (0 ight tats)
Zag 2a (0 le rtatons)
See
Factors require for selecting typeof rotation
The following ae the factors wed for selecting type of rotation:
Does the node whi we are ying to ote havea gradparcar?
she ode el ight elo he prea?
sth node lef or ih child ofthe grandparent”
(Coss forthe Rotations
(Case 1: ithe node doesnt have agra pasea, ad if it isthe ight cil ofthe pea. then we
‘ary out the lef tation: others, the ight rotation is porformed
(Case 2 he node hs a grparnt, then bese 0 the
be performed:
Soenaie 1: Ifthe node i peat i aso sight fs pea, then ag
{rich righ raion spool
Scenario 2: Ifthe node i eo ‘right of ts pret thn ig ae ihe
{eft rotation s prone.
lowing scenarios: the rotation would
Soenaria 3:1 he mn reheat ante REN eis HE hen lef
© scanned with OKEN Scanner10:52 OW Ss OG rm al 31%
Shield® Level Annuities
Ad A Level Of Protection, Growth Opp.
tee
© Bethe pe eft or it hil ofthe parent?
Tsthe nde let right ei ofthe prandarent
(Cases forthe Rotations
(Case 1: the pode does not haves gral-pre, an it the ght cid of he prea, then we
carry ou the el tation: otherwine, the it tion spre
(Case 2: the node has prandparet, then sed on the following scenario the tation would
te prformed:
Seemari I the noe he right of he pars nthe prea also right of ts paren then ie
sip right right rotation s performs.
Seenaio 2:1 he node i ef ofa peat, but the pea is ight of ts pura. hen ig 2a right
eft rnation sexo
Seemaio 3 1 he node righ ofthe penta the pets ight of spe, he i et
Iefrttion spre,
Scenario 4: the node right of paren, bu the pare et ots parent, then ig 2 igh
ep rutin spied
[Now ets understand the above rotations wih examples.
To rearange the tre, we med to perms some rotations. The following ae the types a
rotations nthe spay te
© Zig rotations
The ig rotations are wed when the em oe searched is ier ont nae othe chil fart
ode (et the gh hi),
"The fllowing are the cases that ea exist in
he spay tree while searching
(Case 2 Ifthe earch itm sa sil ofthe ro oe, then he to scenarios wil Be ter:
1. the cil se hil the sgh tation would he performed, Know as ai i
IF th child righ chi, he ef rotation woud be performed, known a 82g et
Let's look tthe above two scenarios throxgh an example
Consider the below example:
Tithe above example, weave to search 7 elmer athe wee. We wl follow the below sep:
Sty 2 Ome he cnet aS
he The righ ation is performed 50
© scanned with OKEN Scanner10:53 OY ¢ Oe em all 31%
0 Shield® Level Annuities ; x
Ad + A Level Of Protection, Growth Opp.
Let's lok atthe above two scenarios through an example
Conser the below any
Inthe above example, we have
Step 1: Fir, we compe 7 with coo me
le,
Step 2 Once the elements found we will perform spying, Te Hit oto s performed so
that? poomes th oot de of there, show Belo
scar 7 element in the tee, We wl follow the below steps
Tess thin 10, st eid of he rot
Let's consider another example
Inthe above example, we hive 1 scrch 20 ement ia the ee. We wil oll the bebo steps:
Step 1: Fist we compare 20 with a oot and. AS 20 preter than the rot nde, ight
child of the oot ade.
A
i pertonm spaying, Te let
Step 2¢ Once the cme is
ttt 20 clement feos he
i
© scanned with OKEN Scanner10:53 ONG * OG rem al 31%
Shield® Level Annuities
Ad - A Level Of Protection, Growth Opp.
x
© Fig tg rtatons
andparem. In hs ease, we have to perform four rtatons or saying
Lets understand this ase tho
on example
Suppose we hive to search| ck ment inthe tre, which is shown below
Step 1: Fest, we have to peor a standard BST searching operation i one to scurch the 1
leet, As 1 i ss tn 10 ad 740i wll be a the et ofthe node 7. Three, element 1s
ise, we fave to prt
In order to mae nde 183 root ns, we meet perform 80 right rotations known si ie
rittinns, When we pecorm the igh ration then 10 will os
come upward as shown in the below igre:
eroari)
© scanned with OKEN Scanner10:53 OW * OB eh ll 31%
0 Shield® Level Annuities : x
Ad - A Level Of Protection, Growth Opp.
eee ee
© scanned with OKEN Scanner10:53 OMG * OG rm al 31%
Shield® Level Annuities : x
Ad + A Level Of Protection, Growth Opp.
tpwards as shown below
Suppose we want to search 20 the low te.
In onder wo search 20, we need wo perform welt rotations, Following are the steps ruled wo
seat 20 nade
© scanned with OKEN Scanner10:53 OMG * OG rm al 31%
Shield® Level Annuities
Ad + A Level Of Protection, Growth Opp.
x
Step I: Fis, we perfonn the standard BST searching operation. As 20 greater tan 10 a 15
sort willbe abe sigh
Step 2: The second 3
te o perform playing. In this eae, two fet rotations woul! be
© scanned with OKEN Scanner10:53 OWS + OG te ul ste
Shield® Level Annuities : x
Ad A Level Of Protection, Growth Opp.
Inthe second et
oe 15 will move downwards, and noe 20 besomes the ook aod of
thee, shown below
performed s0
brown as rig rig let
ga tations
Ti pow, we have read that both p
Now, we will eet RL or LR relations
ue the patent al degrade
[Let'sundertand this case through an example
Seppose we wast to scurch 13 elem inthe ee which s shown below
© scanned with OKEN Scanner10:53 OMG * OG rm al 31%
Shield® Level Annuities
Ad - A Level Of Protection, Growth Opp.
x
Step 1: First, we perform standart BST serching operation A 13 is preter thin 10 but ss
than 15, so node 13 wl be the ef child ode 15,
Step 2: Since node 13 is atthe lel of 1S and made IS is atthe right of node 10, 20 RL
relationship exist. Fst, e perform he rig rttion on ode 1, an 1S will move downs
{nd node 13 wil ome parts, shown Del
© scanned with OKEN Scanner10:53 OMG * OG rm al 31%
Shield® Level Annuities
Ad A Level Of Protection, Growth Opp.
x
Ac me can obser inthe above tee tht node 13 has Pecome the root ode: therefore, the
searching is completed. In this cise, we hive fist performed the zig rottion al then 23g
2 2g rotation
Lets understand this case through an example,
ST searching operation, Aisles than 10 ft gest
Step 2: Since onde 9 sat the righ of nade 7
lola)
and node 7 isa the left of nade 10, 50 LR
‘on mode 7. The node 7 sil move
© scanned with OKEN Scanner3SOOBe OG rm al 31%
Shield® Level Annuities : x
Ad - A Level Of Protection, Growth Opp.
Sep 1: Fi, we perform the salad AST serching operation. As 9 es than 10 bt caer
han 7, ot wl be the righ child f ode 7
2 nade 9 i a the sight of node 7, ant node 7 atthe et of mode 10, 50 LR
ip exis Fit, we peso the Ie coation
town below
maton koe ion Aft ecto
own bebo
© scanned with OKEN Scanner10:53 OMG * OG re al 31%
Shield® Level Annuities : x
Ad A Level Of Protection, Growth Opp.
As we can ofmerve fn the above tre that aod 13 sa rot de; three, the searching i
complete. {a ths cme, we have frst perfried the zag rotation (eft tation}, aad then ig
Advanages of Spy tee
In the splay tree, we dom na to sore the extra information. In contain AVL tes,
‘we moe to ore the hance factor ofeach ne that reuies ex space, and Re Black
tres ako requie to ore one extra bit of information that denotes the color of the node,
© Ii the ftest pe of Binary Search tie fr various practical applications. 1 is ued
in Windows Nand GCC compilers,
© It peovies baer performance a he fequetly acessed nodes will move nearer tothe
root rae, eo which the eles cam he accessed guickly im play tees, ed in
the coche implementation a he reenty accessed data tors in he cache 80 tha
‘dont need to 0 to the memory fr accessing the aa, apd itakes es ine.
Drawhack oF Spay ce
“The major drahack ofthe spy to rly balanced i. they are
‘oughly baled, Sometimes the wit tke OW tine complex
68 of 76
Insertion operation in play tree
In the insertion operation, we fst inset the element inthe tee and then erm the slaying
‘operation onthe inserted lem
© scanned with OKEN Scanner10:53 ONG OG rem al 31%
Shield® Level Annuities
Ad A Level Of Protection, Growth Opp.
tee
the cache implementation asthe eecemly accessed data i tre ia dhe cache 50 that we
‘do wt zed 0 go 1 th memory Fr accessing the dat, a takes ess ine
Drawhack of Spay ree
that tres arent sry balance, i they are
he splay toes are ns, 3 wil tke OC) tne comple
asersion operation in Spay tree
In the tntertion operation. we fit inset the element in te ee and then perform the slaying
operation on tbe sete element
‘Step I: Fine inert node 15 in the res. Afr insertion, we ned to pform spaying. As 156
‘arnt nade so we do ct ped to perfor paying.
‘Step 2: The ext clement is 10. As IDs ss tha 15, 30 noe 10 wile the ef ilo ode 15
ss show elo
Now, we peformaplying. To ke 10 a a roc ane, we wil perform dhe ight rttion. as
23: The oa element 17. As 17 peer han 10 and 18 so wll come the ht ei
Now, we wil perform slaying. 17 is having a parent as wll as «grandparent s0 we
perform ig zg rotations
Foard)
© scanned with OKEN Scanner10:53 0G * OG ter all 30%
Shield® Level Annuities : x
Ad A Level Of Protection, Growth Opp.
‘Step 3: The next clement is 17. As 17 i greater than 10 and 15 soit wil Boome th
of mode IS
Mow, we will perforce splayg. As 17 is having pret we
he above figure, we can observe that 17 becomes the roe node ofthe ee; ttf, te
iserion s completed.
‘Step 4 The ext clement 7, AS 7 estan 17,18, an 1D, 0 node 7 will eet hl 0
Now, we have to sp
x. As 7 is having a patent as well
pire 0 we wll
o
© scanned with OKEN Scanner10:53 OW Gi * OG em all 30%
Shield® Level Annuities
Ad + ALevel Of Protection, Growth Opp.
Whe
Sil he ode 7 isnot a oot Rods iis Fe il ofthe rot node, Ke IT, So, We es 0
perform one more righ rotation to make node 7a aoe mde ae shown below
x
Deletion in Splay tree
[As we Know that spy toes ae the variants ofthe Binary’ such tse, so dektion operation
the splay tee woul be imi to ue BST, tut he only ference sate delete operation
tool isp esby he
Typos ot Dean
“Therein on ype dso
Im foriomun spline, fist we delete the element ftom th tee and then we perform the
© scanned with OKEN Scanner10:54 Ef) Ge * OB eh ull 30%.
Shield® Level Annuities
Ad - A Level Of Protection, Growth Opp.
ea
Deletion in Splay tree
[As we know tit spy tes are the variants ofthe Binary search tee, 0 deletion operation in
the spy tree would he sna the BST. but he ony diferent the delete operation is
foto in play trees by he splay
‘Types of Deletions
“There ae to type of detions in the spy roe
1, Botonvup spaying
2. Top-downsphying
Boxtom-up slaying
In botomvup spaying, fist we delete the clement fom the uce and then we perform the
splay onthe deleted ade
Let's understand the deletion nthe Splay tre.
Soppose we want to dss 12,1 frm the tre own below
First we snplypeform the stanford BST deltion operation wo dete 12 element As 12
ina feat node, we simply delete the node from the te.
operation
‘The deletion i still so completed. We nee splay the parent of the dota mode, Le 1, We
have to perform Splay(0) om the tse, As we can observe in the above tee hat 10 is at he Fight
fot mde, and we 7 isa the fel of toe 13 So, Fst, we perform the eft oon om poe 7
tnd then we pesinm the right matin on node [3a shown below
ce §
© scanned with OKEN Scanner10:54 OW Ge OG te ull 30%
Shield® Level Annuities
Ad « A Level Of Protection, Growth Opp.
x
Whgtth
Sil, 10 swt a root node nde 104 the eid ofthe root node. So, we ned © pform
the righ station on he oot no, i. Ht make node 13 Yot noe as own eo
vate a
Now we have to delete the 14 element rom he tre, which is shown below
[As we know that we cana simply delete the itermal node, We will replace the we of the
tds ether sing inorder predecessor or inorder succor. Suppose we vse inner ec in
Stich we replace the sala wth the Towest ath exit i th ight subue, The lowest valve
Inthe ight suluee of mode 14 is 15, so we replete vale 1 wit 15. Since mde 1 becomes
the lane, so we ca imply delete tas shown below
Sil, the dekstion snot completed, We neal to perform one mare operation, Le. spying in
snc we ead to make the pseu of the deleted mode asthe rot node. Before deletion, the
© scanned with OKEN Scanner10:54 BW * OG ee ull 30%]
Shield® Level Annuities : xX
Ad- A Level Of Protection, Growth Opp. .
Sill, the deletion isnot competed. We nea to perform one more operation. sping in
‘which we cod to make the pore of the deltod noe a the rot nade. Hetore dean, the
peat of re Lf was the ot nade, 10, w0 we do me oprform any playing inthis case
“Top-down playing
In top-down slaying we fst perform the spaying om which the deletion isto be perfor an
thon dekte the nae from the tre. One the clement is deleted, we will perform the join
Le’ understand the top-down spaying through an example,
Soppose we want to dete 16 rom the tree which is shown below
Step 1: In top-down slaying, fist we poor spaying on the noe 16. The
pent as wll as grandparent. The mode 16a the ight fs parent ad the paren
th ig fis paral soi zap zap suai, La this case, ft, we wll por d
rotation om ode 1 an the 1 3 shown eo
© scanned with OKEN Scanner10:54 BS & ¢ OG ter all 30%
€ DOC-20240129-WA0007.
Shield® Level Annuities
Ad + A Level Of Protection, Growth Opp.
‘Step I In top down slaying ist we perform playing om the mode 16, The ode 16s oth
paren swell as grace, The node 16 the right of ts psa a he pent
atthe Fight of ts pea, x his ag 2g sation. ths ease est, e wl pt
toting on node 13 and then 14 naw below
left rotation onthe nade 12 40 make aode 16 2 root node,
“nes
(Once the node 16 becomes a for ode, we wil delete he node 16 and we wil get two diferent
trees ft subtree and right sutras shown below
oo °
cB 2 A & :
Rename Edit Bookmark Share More
© scanned with OKEN Scanner4 OME + OG Fall 30%
Shield® Level Annuities
Ad - A Level Of Protection, Growth Opp.
"HEN
Once the made 16 becomes a ot de, we wl elt he node 16nd we wil gt tn fret
tres Jef sbtree aight sore show low
x
[Ax we how that the vale ofthe left sree are aha lester than the vals of the ight
subuce. The root ofthe estes 12 andthe oo ofthe righ sburcei 17. The Bist tp so
find the asin sce. Inthe eft sulce,the msm creat i 15,
anu hen we ood wo perf splay
[As we can obve in the above tee tha the client 1 is having a pants well as a
fandparem. A node is it of ts paret and the pare: node is also rit ofits pret, 9 We
ed o perform two I ottions to muke node 15 rot nee as shown Below
an this operation i own soln op
de 17 athe gh pr ofthe 15 a8 shown below
5 Ay
© scanned with OKEN Scanner