0% found this document useful (0 votes)
224 views

DSA Unit - II Trees

Uploaded by

Irene Thomas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
224 views

DSA Unit - II Trees

Uploaded by

Irene Thomas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

Unit - II

Trees

By
Ms. Ankita P. Shinde

Data Structures and Algorithms


Tree
In linear data structure data is organized in sequential order and in non-linear data
structure data is organized in random order. A tree is a very popular non-linear data
structure used in a wide range of applications. A tree data structure can be defined as
follows...
“Tree is a non-linear data structure which organizes data in hierarchical structure
and this is a recursive definition.”
A tree data structure can also be defined as follows...
“Tree data structure is a collection of data (Node) which is organized in
hierarchical structure recursively.”

Data Structures and Algorithms Unit – II Trees


Tree
In tree data structure, every individual element is called as Node. Node in a tree data
structure stores the actual data of that particular element and link to next element in
hierarchical structure.
In a tree data structure, if we have N number of nodes then we can have a maximum
of N-1 number of links.

Data Structures and Algorithms Unit – II Trees


Basic Terminology
1. Root
In a tree data structure, the first node is called as Root Node. Every tree must have a root
node. We can say that the root node is the origin of the tree data structure. In any tree,
there must be only one root node. We never have multiple root nodes in a tree.

Data Structures and Algorithms Unit – II Trees


Basic Terminology
2. Edge
In a tree data structure, the connecting link between any two nodes is called as EDGE. In a
tree with 'N' number of nodes there will be a maximum of 'N-1' number of edges.

Data Structures and Algorithms Unit – II Trees


Basic Terminology
3. Parent
In a tree data structure, the node which is a predecessor of any node is called as PARENT
NODE. In simple words, the node which has a branch from it to any other node is called a
parent node. Parent node can also be defined as "The node which has child / children".

Data Structures and Algorithms Unit – II Trees


Basic Terminology
4. Child
In a tree data structure, the node which is descendant of any node is called as CHILD
Node. In simple words, the node which has a link from its parent node is called as child
node. In a tree, any parent node can have any number of child nodes. In a tree, all the
nodes except root are child nodes.

Data Structures and Algorithms Unit – II Trees


Basic Terminology
5. Siblings
In a tree data structure, nodes which belong to same Parent are called as SIBLINGS. In
simple words, the nodes with the same parent are called Sibling nodes.

Data Structures and Algorithms Unit – II Trees


Basic Terminology
6. Leaf
In a tree data structure, the node which does not have a child is called as LEAF Node. In
simple words, a leaf is a node with no child.
In a tree data structure, the leaf nodes are also called as External Nodes. External node is
also a node with no child. In a tree, leaf node is also called as 'Terminal' node.

Data Structures and Algorithms Unit – II Trees


Basic Terminology
7. Internal Nodes
In a tree data structure, the node which has atleast one child is called as INTERNAL Node.
In simple words, an internal node is a node with atleast one child.
In a tree data structure, nodes other than leaf nodes are called as Internal Nodes. The
root node is also said to be Internal Node if the tree has more than one node. Internal
nodes are also called as 'Non-Terminal' nodes.

Data Structures and Algorithms Unit – II Trees


Basic Terminology
8. Degree
In a tree data structure, the total number of children of a node is called as DEGREE of that
Node. In simple words, the Degree of a node is total number of children it has. The highest
degree of a node among all the nodes in a tree is called as 'Degree of Tree'

Data Structures and Algorithms Unit – II Trees


Basic Terminology
9. Level
In a tree data structure, the root node is said to be at Level 0 and the children of root node
are at Level 1 and the children of the nodes which are at Level 1 will be at Level 2 and so
on... In simple words, in a tree each step from top to bottom is called as a Level and the
Level count starts with '0' and incremented by one at each level (Step).

Data Structures and Algorithms Unit – II Trees


Basic Terminology
10. Height
In a tree data structure, the total number of edges from leaf node to a particular node in
the longest path is called as HEIGHT of that Node. In a tree, height of the root node is said
to be height of the tree. In a tree, height of all leaf nodes is '0'.

Data Structures and Algorithms Unit – II Trees


Basic Terminology
11. Depth
In a tree data structure, the total number of egdes from root node to a particular node is
called as DEPTH of that Node. In a tree, the total number of edges from root node to a leaf
node in the longest path is said to be Depth of the tree. In simple words, the highest
depth of any leaf node in a tree is said to be depth of that tree. In a tree, depth of the
root node is '0'.

Data Structures and Algorithms Unit – II Trees


Basic Terminology
12. Path
In a tree data structure, the sequence of Nodes and Edges from one node to another node
is called as PATH between that two Nodes. Length of a Path is total number of nodes in
that path. In below example the path A - B - E - J has length 4.

Data Structures and Algorithms Unit – II Trees


Basic Terminology
13. Sub Tree
In a tree data structure, each child from a node forms a subtree recursively. Every child
node will form a subtree on its parent node.

Data Structures and Algorithms Unit – II Trees


Types of Trees in Data Structure
General tree: The general tree is one of the types of tree data structure. In the general
tree, a node can have either 0 or maximum n number of nodes. There is no restriction
imposed on the degree of the node (the number of nodes that a node can contain). The
topmost node in a general tree is known as a root node. The children of the parent node are
known as subtrees.

Data Structures and Algorithms Unit – II Trees


Types of Trees in Data Structure
2. Binary Tree

Here, binary name itself suggests two numbers, i.e., 0 and 1. In a binary tree, each node in
a tree can have utmost two child nodes. Here, utmost means whether the node has 0
nodes, 1 node or 2 nodes.

Data Structures and Algorithms Unit – II Trees


Types of Trees in Data Structure
3. Binary Search Tree

Binary search tree is a non-linear data structure in which


one node is connected to n number of nodes. It is a node-
based data structure. A node can be represented in a
binary search tree with three fields, i.e., data part, left-
child, and right-child. A node can be connected to the
utmost two child nodes in a binary search tree, so the node
contains two pointers (left child and right child pointer).

Every node in the left subtree must contain a value less


than the value of the root node, and the value of each node
in the right subtree must be bigger than the value of the
root node.

Data Structures and Algorithms Unit – II Trees


Types of Binary Tree in Data Structure
There are different types of binary trees and they are...
1. Strictly Binary Tree
A binary tree in which every node has either two or zero number of children is called
Strictly Binary Tree
Strictly binary tree is also called as Full Binary Tree or Proper Binary Tree or 2-Tree

Strictly binary tree data structure is used to represent mathematical expressions.

Data Structures and Algorithms Unit – II Trees


Types of Binary Tree in Data Structure
2. Complete Binary Tree
A binary tree in which every internal node has exactly two children and all leaf nodes are
at same level is called Complete Binary Tree.
Complete binary tree is also called as Perfect Binary Tree.

Data Structures and Algorithms Unit – II Trees


Types of Binary Tree in Data Structure
3. Extended Binary Tree
The full binary tree obtained by adding dummy nodes to a binary tree is called as
Extended Binary Tree.

In above figure, a normal binary tree is converted into full binary tree by adding dummy
nodes (In pink colour).

Data Structures and Algorithms Unit – II Trees


Binary Tree Representations
A binary tree data structure is represented using two methods. Those methods are as
follows...
1.Array Representation
2.Linked List Representation
Consider the following binary tree...

Data Structures and Algorithms Unit – II Trees


Binary Tree Representations
1. Array Representation of Binary Tree
In array representation of a binary tree, we use one-
dimensional array (1-D Array) to represent a binary
tree.
Consider the example of a binary tree and it is
represented as follows...

To represent a binary tree of depth 'n' using array representation, we need one
dimensional array with a maximum size of 2n + 1.

Data Structures and Algorithms Unit – II Trees


Binary Tree Representations
2. Linked List Representation of Binary Tree
We use a double linked list to represent a binary tree. In a double linked list, every node
consists of three fields. First field for storing left child address, second for storing actual
data and third for storing right child address.
In this linked list representation, a node has the following structure...

The example of the binary tree represented using Linked list representation is shown as
follows...

Data Structures and Algorithms Unit – II Trees


Binary Tree Representations
2. Linked List Representation of Binary Tree

Data Structures and Algorithms Unit – II Trees


Tree Representations
A tree data structure can be represented in two methods. Those methods are as follows...
1. List Representation
2. Left Child - Right Sibling Representation
Consider the following tree...

Data Structures and Algorithms Unit – II Trees


Tree Representations
1. List Representation
In this representation, we use two types of nodes one for representing the node with data
called 'data node' and another for representing only references called 'reference node'. We
start with a 'data node' from the root node in the tree. Then it is linked to an internal node
through a 'reference node' which is further linked to any other node directly. This process
repeats for all the nodes in the tree.
The above example tree can be represented using List representation as follows...

Data Structures and Algorithms Unit – II Trees


Tree Representations
2. Left Child - Right Sibling Representation
In this representation, we use a list with one type of node which consists of three fields namely Data
field, Left child reference field and Right sibling reference field. Data field stores the actual value of a
node, left reference field stores the address of the left child and right reference field stores the
address of the right sibling node. Graphical representation of that node is as follows...

In this representation, every node's data field stores the actual value of that node. If that node has
left a child, then left reference field stores the address of that left child node otherwise stores NULL. If
that node has the right sibling, then right reference field stores the address of right sibling node
otherwise stores NULL.
The above example tree can be represented using Left Child - Right Sibling representation as
follows...

Data Structures and Algorithms Unit – II Trees


Tree Representations

Data Structures and Algorithms Unit – II Trees


Convert a General Tree to Binary Tree
Following are the rules to convert a General Tree to Binary Tree:
1. The root of the Binary Tree is the Root of the Generic Tree.
2. The left child of a node in the Generic Tree is the Left child of that node in the Binary
Tree.
3. The right sibling of any node in the Generic Tree is the Right child of that node in the
Binary Tree.
Examples:
Convert the following Generic Tree to Binary Tree:

Data Structures and Algorithms Unit – II Trees


Convert a General Tree to Binary Tree
Solution:

Data Structures and Algorithms Unit – II Trees


Binary Tree Traversals
• Ordered rooted trees are often used to store information.
• We need procedures for visiting each vertex of an ordered rooted tree to access data.
Several important algorithms for visiting all the vertices of an ordered rooted tree
• Ordered rooted trees can also be used to represent various types of expressions,
such as arithmetic expressions involving numbers, variables, and operations.
• Procedures for systematically visiting every vertex of an ordered rooted tree are
called Traversal algorithms.
• Traversal algorithms : Pre-order traversal, In-order traversal, Postorder
traversal.

Data Structures and Algorithms Unit – II Trees


Binary Tree Traversals
Pre-order traversal: (Root, Left, Right)
Visit root, visit subtrees left to right

Data Structures and Algorithms Unit – II Trees


Binary Tree Traversals
Pre-order traversal: (Root, Left, Right)
Visit root, visit subtrees left to right

Data Structures and Algorithms Unit – II Trees


Binary Tree Traversals
In-order traversal: (Left, Root, Right)
Visit leftmost subtree, visit root, visit other subtrees left to right

Data Structures and Algorithms Unit – II Trees


Binary Tree Traversals
In-order traversal: (Left, Root, Right)
Visit leftmost subtree, visit root, visit other subtrees left to right

Data Structures and Algorithms Unit – II Trees


Binary Tree Traversals
Post-order traversal: (Left, Right, Root)
Visit subtrees left to right; visit root

Data Structures and Algorithms Unit – II Trees


Binary Tree Traversals
Post-order traversal: (Left, Right, Root)
Visit subtrees left to right; visit root

Data Structures and Algorithms Unit – II Trees


Binary Tree Traversals Recursive Approach
In every traversal we visit the tree in certain order.
Preorder Traversal:
• Visit the root.
• Visit the left-subtree.
• Visit the right-subtree.
Inorder Traversal:
• Visit the left-subtree.
• Visit the root.
Preorder Traversal: 1 2 4 5 3 6 7
• Visit the right-subtree.
Inorder Traversal: 4 2 5 1 6 3 7
Postorder Traversal:
Postorder Traversal: 7 6 3 5 4 2 1
• Visit the right-subtree.
• Visit the left-subtree.
• Visit the root.

Data Structures and Algorithms Unit – II Trees


Inorder Tree Traversal – Non Recursive Approach
1.Create a Stack.
2.Push the root into the stack and set the root = root.left continue till it hits the NULL.
3.If root is null and Stack is empty Then
1. return, we are done.
4.Else
1. Pop the top Node from the Stack and set it as, root = popped_Node.
2. print the root and go right, root = root.right.
3. Go to step 2. See the animated image

5.End If

Data Structures and Algorithms Unit – II Trees


Preorder Tree Traversal – Non Recursive Approach
Given a binary tree, write a non recursive or iterative algorithm for preorder traversal.

Since we are not using recursion, we will use the Stack to store the traversal, we need to
remember that preorder traversal is, first traverse the root node then left node followed by the
right node.

Data Structures and Algorithms Unit – II Trees


Preorder Tree Traversal – Non Recursive Approach
1.Create a Stack.
2.Print the root and push it to Stack and go left i.e root=root.left and till it hits the NULL.
3.If root is null and Stack is empty Then
1. return, we are done.
4.Else
1. Pop the top Node from the Stack and set it as, root = popped_Node.
2. Go right, root = root.right.
3. Go to step 2. See the animated image
5.End If

Data Structures and Algorithms Unit – II Trees


Postorder Tree Traversal – Non Recursive Approach
Given a binary tree, write a non recursive or iterative algorithm for postorder traversal.

• We have seen how we do inorder and preorder traversals without


recursion using Stack, But post order traversal will be different and
slightly more complex than other two. Reason is post order is non-
tail recursive ( The statements execute after the recursive call).
• If you just observe here, postorder traversal is just reverse of
preorder traversal (1 3 7 6 2 5 4 if we traverse the right node first
and then left node.)
• So idea is follow the same technique as preorder traversal and
instead of printing it push it to the another Stack so that they will
come out in reverse order (LIFO).
• At the end just pop all the items from the second Stack and print it.

Data Structures and Algorithms Unit – II Trees


Postorder Tree Traversal – Non Recursive Approach
1.Push root into Stack_One.
2.while(Stack_One is not empty)
1. Pop the node from Stack_One and push it into Stack_Two.
2. Push the left and right child nodes of popped node into Stack_One.
3.End Loop
4.Pop out all the nodes from Stack_Two and print it.
See the animated image

Data Structures and Algorithms Unit – II Trees


Example
Example: Consider the following tree given in the problem. Show a Postorder, Preorder and
In order Traversal of tree.

Solution:
Preorder Sequence : 50, 17, 12, 9, 14, 23, 19, 72, 54, 67, 76.
Inorder Séquence : 9, 12, 14, 17, 23, 19, 50, 54, 67, 72, 76.
Postorder Sequence : 9, 14, 12, 19, 23, 17, 67, 54, 76, 72, 50.

Data Structures and Algorithms Unit – II Trees


Example
Example: From the given traversals construct the binary tree.
Pre-order: G, B, Q, A, C, K, F, P, D, E, R, H
In-order: Q, B, K, C, F, A, G, P, E, D, H, R
Solution:
Step 1 : The first element in preorder sequence is root or parent node. We will locate this
element in inorder sequence. Here the first pre-order element is G. Now, in the inorder
sequence the list left to G forms left subbranch and the sequence right to G forms the right
sub branch.

Data Structures and Algorithms Unit – II Trees


Example
We will repeat the above procedure for each sub-branch
Step 2:
Pre-order: G, B, Q, A, C, K, F, P, D, E, R, H
In-order: Q, B, K, C, F, A, G, P, E, D, H, R

Data Structures and Algorithms Unit – II Trees


Example
Step 3:

Data Structures and Algorithms Unit – II Trees


Example
Step 4:

Data Structures and Algorithms Unit – II Trees


Depth and Level Wise Traversals
Breadth-First Search (BFS) and Depth-First Search (DFS) are algorithms for traversing
graphs or tree. Traversal is the process of accessing each vertex (node) of a data
structure in a systematic well-defined order. Choosing the algorithm depends on the type
of data you are dealing with.
There are generally two types of traversal and the main difference between them is in the
order they access nodes:
• Breadth-first search
• Depth-first search

Data Structures and Algorithms Unit – II Trees


Breadth-first search
BFS search nodes level by level, starting from the root node. Then checking its children.
Then children for children and so on. Until all nodes are processed or node which satisfies
search condition is found.

Data Structures and Algorithms Unit – II Trees


Breadth-first search
For example, assume you need to find node with value 1 in the following tree.

Yellow cell are cells which are tested in search algorithm before needed node found.

Data Structures and Algorithms Unit – II Trees


Depth-First Search (DFS)
DFS behave differently. It checks all nodes from leftmost path from the root to the leaf, then
jumps up and check right node and so on.

Data Structures and Algorithms Unit – II Trees


Depth-First Search (DFS)
For example, assume you need to find node with value 1 in the following tree.

Yellow cell are cells which are tested in search algorithm before needed node found. Take
into account that for some cases DFS require less nodes for processing. For some cases
it requires more.

Data Structures and Algorithms Unit – II Trees


Huffman’s Tree
Huffman coding is a lossless data compression algorithm. The idea is to assign variable-
length codes to input characters, lengths of the assigned codes are based on the
frequencies of corresponding characters. The most frequent character gets the smallest
code and the least frequent character gets the largest code.
There are mainly two major parts in Huffman Coding
• Build a Huffman Tree from input characters.
• Traverse the Huffman Tree and assign codes to characters.

Data Structures and Algorithms Unit – II Trees


Huffman’s Tree
Steps to build Huffman Tree
Input is an array of unique characters along with their frequency of occurrences and output is
Huffman Tree.
1. Create a leaf node for each unique character and build a min heap of all leaf nodes (Min
Heap is used as a priority queue. The value of frequency field is used to compare two nodes
in min heap. Initially, the least frequent character is at root)
2. Extract two nodes with the minimum frequency from the min heap.
3. Create a new internal node with a frequency equal to the sum of the two nodes frequencies.
Make the first extracted node as its left child and the other extracted node as its right child.
Add this node to the min heap.
4. Repeat steps#2 and #3 until the heap contains only one node. The remaining node is the
root node and the tree is complete.
Let us understand the algorithm with an example:

Data Structures and Algorithms Unit – II Trees


Huffman’s Tree
Let us understand the algorithm with an example:
character Frequency
a 5
b 9
c 12
d 13
e 16
f 45

Data Structures and Algorithms Unit – II Trees


Huffman’s Tree
Step 1. Build a min heap that contains 6 nodes where each node represents root of a tree
with single node.
Step 2 Extract two minimum frequency nodes from min heap. Add a new internal node with
frequency 5 + 9 = 14.

Now min heap contains 5 nodes where 4 nodes are roots of trees with single element each,
and one heap node is root of tree with 3 elements
character Frequency
c 12
d 13
Internal Node 14
e 16
f 45

Data Structures and Algorithms Unit – II Trees


Huffman’s Tree
Step 3: Extract two minimum frequency nodes from heap. Add a new internal node with
frequency 12 + 13 = 25.

Now min heap contains 4 nodes where 2 nodes are roots of trees with single element each,
and two heap nodes are root of tree with more than one nodes
character Frequency
Internal Node 14
e 16
Internal Node 25
f 45

Data Structures and Algorithms Unit – II Trees


Huffman’s Tree
Step 4: Extract two minimum frequency nodes. Add a new internal node with frequency 14 +
16 = 30

Now min heap contains 3 nodes.


character Frequency
Internal Node 25
Internal Node 30
f 45

Data Structures and Algorithms Unit – II Trees


Huffman’s Tree
Step 5: Extract two minimum frequency nodes. Add a new internal node with
frequency 25 + 30 = 55

Now min heap contains 2 nodes.


character Frequency
f 45
Internal Node 55

Data Structures and Algorithms Unit – II Trees


Huffman’s Tree
Step 6: Extract two minimum frequency nodes. Add a new internal node with frequency
45 + 55 = 100.

Now min heap contains only one node.


character Frequency
Internal Node 100
Since the heap contains only one node, the algorithm stops here.

Data Structures and Algorithms Unit – II Trees


Huffman’s Tree
Steps to print codes from Huffman Tree:
Traverse the tree formed starting from the root. Maintain an auxiliary array. While
moving to the left child, write 0 to the array. While moving to the right child, write 1 to
the array. Print the array when a leaf node is encountered.

The codes are as follows:


character code-word
f 0
c 100
d 101
a 1100
b 1101
e 111

Data Structures and Algorithms Unit – II Trees


Binary Search Tree
In a binary tree, every node can have a maximum of two children but there is no need to
maintain the order of nodes basing on their values. In a binary tree, the elements are
arranged in the order they arrive at the tree from top to bottom and left to right.
A binary tree has the following time complexities...
1.Search Operation - O(n)
2.Insertion Operation - O(1)
3.Deletion Operation - O(n)
Binary Search Tree is a binary tree in which every node contains only smaller
values in its left subtree and only larger values in its right subtree.

Data Structures and Algorithms Unit – II Trees


Binary Search Tree
In a binary search tree, all the nodes in the left subtree of any node contains smaller values
and all the nodes in the right subtree of any node contains larger values as shown in the
following figure...

Data Structures and Algorithms Unit – II Trees


Binary Search Tree
Example
The following tree is a Binary Search Tree. In this tree, left subtree of every node
contains nodes with smaller values and right subtree of every node contains larger
values.

Every binary search tree is a binary tree but every binary tree need not to be binary
search tree.

Data Structures and Algorithms Unit – II Trees


Binary Search Tree
Example: Search element 27

Data Structures and Algorithms Unit – II Trees


Binary Search Tree
Operations on a Binary Search Tree
The following operations are performed on a binary search tree...
1.Search
2.Insertion
3.Deletion

Data Structures and Algorithms Unit – II Trees


Binary Search Tree
Search Operation in BST
In a binary search tree, the search operation is performed with O(log n) time complexity.
The search operation is performed as follows...
Step 1 - Read the search element from the user.
Step 2 - Compare the search element with the value of root node in the tree.
Step 3 - If both are matched, then display "Given node is found!!!" and terminate the
function
Step 4 - If both are not matched, then check whether search element is smaller or larger
than that node value.
Step 5 - If search element is smaller, then continue the search process in left subtree.
Step 6- If search element is larger, then continue the search process in right subtree.
Step 7 - Repeat the same until we find the exact element or until the search element is
compared with the leaf node
Step 8 - If we reach to the node having the value equal to the search value then display
"Element is found" and terminate the function.
Step 9 - If we reach to the leaf node and if it is also not matched with the search element,
then display "Element is not found" and terminate the function.

Data Structures and Algorithms Unit – II Trees


Binary Search Tree
Search Operation in BST
Always initiate analyzing tree at the root node and then move further to either the right or
left subtree of the root node depending upon the element to be located is either less or
greater than the root.

A. The element to be searched is 10


B. Compare the element with the root
node 12, 10 < 12, hence you move
to the left subtree. No need to
analyze the right-subtree
C. Now compare 10 with node 7, 10 >
7, so move to the right-subtree
D.Then compare 10 with the next
node, which is 9, 10 > 9, look in the
right subtree child
E. 10 matches with the value in the
node, 10 = 10, return the value to
the user.

Data Structures and Algorithms Unit – II Trees


Binary Search Tree
Insertion Operation in BST
In a binary search tree, the insertion operation is performed with O(log n) time
complexity. In binary search tree, new node is always inserted as a leaf node. The
insertion operation is performed as follows...
Step 1 - Create a newNode with given value and set its left and right to NULL.
Step 2 - Check whether tree is Empty.
Step 3 - If the tree is Empty, then set root to newNode.
Step 4 - If the tree is Not Empty, then check whether the value of newNode
is smaller or larger than the node (here it is root node).
Step 5 - If newNode is smaller than or equal to the node then move to its left child. If
newNode is larger than the node then move to its right child.
Step 6- Repeat the above steps until we reach to the leaf node (i.e., reaches to NULL).
Step 7 - After reaching the leaf node, insert the newNode as left child if the newNode
is smaller or equal to that leaf node or else insert it as right child.

Data Structures and Algorithms Unit – II Trees


Binary Search Tree
Insertion Operation in BST
This is a very straight forward operation. First, the root node is inserted, then the next
value is compared with the root node. If the value is greater than root, it is added to the
right subtree, and if it is lesser than the root, it is added to the left subtree.

A. There is a list of 6 elements that


need to be inserted in a BST in
order from left to right
B. Insert 12 as the root node and
compare next values 7 and 9 for
inserting accordingly into the right
and left subtree
C. Compare the remaining values 19,
5, and 10 with the root node 12
and place them accordingly. 19 >
12 place it as the right child of 12,
5 < 12 & 5 < 7, hence place it as
left child of 7.
A. Now compare 10, 10 is < 12 & 10
is > 7 & 10 is > 9, place 10 as right
subtree of 9.

Data Structures and Algorithms Unit – II Trees


Binary Search Tree
Deletion Operation in BST
In a binary search tree, the deletion operation is performed with O(log n) time complexity.
Deleting a node from Binary search tree includes following three cases...
Case 1: Deleting a Leaf node (A node with no children)
Case 2: Deleting a node with one child
Case 3: Deleting a node with two children

Case 1: Deleting a leaf node


We use the following steps to delete a leaf node from BST...
Step 1 - Find the node to be deleted using search operation
Step 2 - Delete the node using free function (If it is a leaf) and terminate the function.

Case 2: Deleting a node with one child


We use the following steps to delete a node with one child from BST...
Step 1 - Find the node to be deleted using search operation
Step 2 - If it has only one child then create a link between its parent node and child node.
Step 3 - Delete the node using free function and terminate the function.

Data Structures and Algorithms Unit – II Trees


Binary Search Tree
Case 3: Deleting a node with two children
We use the following steps to delete a node with two children from BST...
Step 1 - Find the node to be deleted using search operation
Step 2 - If it has two children, then find the largest node in its left subtree (OR)
the smallest node in its right subtree.
Step 3 - Swap both deleting node and node which is found in the above step.
Step 4 - Then check whether deleting node came to case 1 or case 2 or else goto step 2
Step 5 - If it comes to case 1, then delete using case 1 logic.
Step 6- If it comes to case 2, then delete using case 2 logic.
Step 7 - Repeat the same process until the node is deleted from the tree.

Data Structures and Algorithms Unit – II Trees


Binary Search Tree
Deletion Operation in BST
Case 1- Node with zero children: this is the easiest situation, you just need to delete
the node which has no further children on the right or left.

A. This is the first case of deletion in


which you delete a node that has
no children. As you can see in the
diagram that 19, 10 and 5 have no
children. But we will delete 19.
B. Delete the value 19 and remove
the link from the node.
C. View the new structure of the BST
without 19

Data Structures and Algorithms Unit – II Trees


Binary Search Tree
Deletion Operation in BST
Case 2 - Node with one child: once you delete the node, simply connect its child node
with the parent node of the deleted value.
A. This is the second case of deletion
in which you delete a node that
has 1 child, as you can see in the
diagram that 9 has one child.
B. Delete the node 9 and replace it
with its child 10 and add a link
from 7 to 10
C. View the new structure of the BST
without 9

Data Structures and Algorithms Unit – II Trees


Binary Search Tree
Deletion Operation in BST
Case 3 Node with two children: this is the most difficult situation, and it works on the
following two rules
3a - In Order Predecessor: you need to delete the node with two children and replace it with
the largest value on the left-subtree of the deleted node

A. Here you will be deleting the node


12 that has two children
B. The deletion of the node will occur
based upon the in order
predecessor rule, which means
that the largest element on the left
subtree of 12 will replace it.
C. Delete the node 12 and replace it
with 10 as it is the largest value on
the left subtree
D.View the new structure of the BST
after deleting 12

Data Structures and Algorithms Unit – II Trees


Binary Search Tree
Deletion Operation in BST
Case 3 Node with two children: this is the most difficult situation, and it works on the
following two rules
3b - In Order Successor: you need to delete the node with two children and replace it
with the smallest value on the right-subtree of the deleted node

A. Delete a node 12 that has two


children
B. The deletion of the node will occur
based upon the In Order Successor
rule, which means that the
smallest element on the right
subtree of 12 will replace it
C. Delete the node 12 and replace it
with 19 as it is the smallest value
on the right subtree
D.View the new structure of the BST
after deleting 12

Data Structures and Algorithms Unit – II Trees


Binary Search Tree
Example: Construct a Binary Search Tree by inserting the following sequence of numbers...
10,12,5,4,20,8,7,15 and 13
Above elements are inserted into a Binary Search Tree as follows...

Data Structures and Algorithms Unit – II Trees


Predecessor And Successor In BST
1. The predecessor of a node in BST is that node that will be visited just before the given node
in the inorder traversal of the tree. If the given node is visited first in the inorder traversal,
then its predecessor is NULL.
2. The successor of a node in BST is that node that will be visited immediately after the given
node in the inorder traversal of the tree. If the given node is visited last in the inorder
traversal, then its successor is NULL.
3. The node for which predecessor and successor are to be found will always be present in the
given tree.
A binary search tree (BST) is a binary tree data structure which has the following properties.
• The left subtree of a node contains only nodes with data less than the node’s data.
• The right subtree of a node contains only nodes with data greater than the node’s data.
• Both the left and right subtrees must also be binary search trees.

Data Structures and Algorithms Unit – II Trees


Predecessor And Successor In BST
Given a binary search tree and integer X. Find the inorder successor and predecessor of a
given X, i.e. return a vector containing the inorder successor and predecessor.

For Example:

The predecessor of 6 is 4
The successor of 6 is 7
The predecessor of 10 is 8
The successor of 10 is 13

Note: If there is no predecessor or successor then add -1 to the answer vector.

Data Structures and Algorithms Unit – II Trees


Predecessor And Successor In BST

Data Structures and Algorithms Unit – II Trees


Threaded Binary Trees
Threaded Binary Tree is also a binary tree in which all left child pointers that are NULL (in
Linked list representation) points to its in-order predecessor, and all right child pointers that
are NULL (in Linked list representation) points to its in-order successor.
Consider the following binary tree..

To convert the above example binary tree


into a threaded binary tree, first find the in-
order traversal of that tree...
In-order traversal of above binary tree...
H-D-I-B-E-A-F-J-C-G

Data Structures and Algorithms Unit – II Trees


Threaded Binary Trees
When we represent the above binary tree using linked list
representation, nodes H, I, E, F, J and G left child pointers
are NULL. This NULL is replaced by address of its in-order
predecessor respectively (I to D, E to B, F to A, J to F and G
In-order traversal of above binary tree...
to C), but here the node H does not have its in-order H-D-I-B-E-A-F-J-C-G

predecessor, so it points to the root node A. And nodes H,


I, E, J and G right child pointers are NULL. These NULL
pointers are replaced by address of its in-order successor
respectively (H to D, I to B, E to A, and J to C), but here the
node G does not have its in-order successor, so it points to
the root node A.
Above example binary tree is converted into threaded
In the above figure, threads are indicated with
binary tree as follows. dotted links.

Data Structures and Algorithms Unit – II Trees


MCQ
1. The number of edges from the root to the node is called __________ of the tree.
a) Height
b) Depth
c) Length
d) Width
Answer: b
Explanation: The number of edges from the root to the node is called depth of the tree.

Data Structures and Algorithms Unit – II Trees


MCQ
2. The number of edges from the node to the deepest leaf is called _________ of the
tree.
a) Height
b) Depth
c) Length
d) Width

Answer: a
Explanation: The number of edges from the node to the deepest leaf is called height of
the tree.

Data Structures and Algorithms Unit – II Trees


MCQ
3. What is a full binary tree?
a) Each node has exactly zero or two children
b) Each node has exactly two children
c) All the leaves are at the same level
d) Each node has exactly one or two children

Answer: a
Explanation: A full binary tree is a tree in which each node has exactly 0 or 2 children.

Data Structures and Algorithms Unit – II Trees


MCQ
4. In a full binary tree if number of internal nodes is I, then number of nodes N are?
a) N = 2*I
b) N = I + 1
c) N = I – 1
d) N = 2*I + 1

Answer: d
Explanation: Relation between number of internal nodes(I) and nodes(N) is N =
2*I+1.

Data Structures and Algorithms Unit – II Trees


MCQ
5. Construct a binary tree by using postorder and inorder sequences given below.
Inorder: N, M, P, O, Q
Postorder: N, P, Q, O, M
a. b. c. d.

Answer: d
Explanation: Here,
Postorder Traversal: N, P, Q, O, M
Inorder Traversal: N, M, P, O, Q
Root node of tree is the last visiting node in Postorder traversal. Thus, Root Node = ‘M’.
The partial tree constructed is:

Data Structures and Algorithms Unit – II Trees


MCQ
6. Which of the following is false about a binary search tree?
a) The left child is always lesser than its parent
b) The right child is always greater than its parent
c) The left and right sub-trees should also be binary search trees
d) In order sequence gives decreasing order of elements

Answer: d
Explanation: In order sequence of binary search trees will always give ascending order
of elements. Remaining all are true regarding binary search trees.

Data Structures and Algorithms Unit – II Trees


MCQ
7. Construct a binary search tree with the below information.
The preorder traversal of a binary search tree 10, 4, 3, 5, 11, 12.
a. b. c. d.

Answer: c
Explanation: Preorder Traversal is 10, 4, 3, 5, 11, 12. Inorder Traversal of Binary search
tree is equal to ascending order of the nodes of the Tree. Inorder Traversal is 3, 4, 5, 10,
11, 12. The tree constructed using Preorder and Inorder traversal is

Data Structures and Algorithms Unit – II Trees


MCQ
8. What is a threaded binary tree traversal?
a) a binary tree traversal using stacks
b) a binary tree traversal using queues
c) a binary tree traversal using stacks and queues
d) a binary tree traversal without using stacks and queues

Answer: d
Explanation: This type of tree traversal will not use stack or queue.

Data Structures and Algorithms Unit – II Trees


MCQ
9. For the tree below, write the in-order traversal.

a) 6, 2, 5, 7, 11, 2, 5, 9, 4
b) 6, 5, 2, 11, 7, 4, 9, 5, 2
c) 2, 7, 2, 6, 5, 11, 5, 9, 4
d) 2, 7, 6, 5, 11, 2, 9, 5, 4

Answer: a
Explanation: In-order traversal follows LNR(Left-Node-Right).

Data Structures and Algorithms Unit – II Trees


MCQ
10. A binary search tree contains values 7, 8, 13, 26, 35, 40, 70, 75. Which one of the following is a valid post-
order sequence of the tree provided the pre-order sequence as 35, 13, 7, 8, 26, 70, 40 and 75?
a) 7, 8, 26, 13, 75, 40, 70, 35
b) 26, 13, 7, 8, 70, 75, 40, 35
c) 7, 8, 13, 26, 35, 40, 70, 75
d) 8, 7, 26, 13, 40, 75, 70, 35

Answer: d
Explanation: The binary tree contains values 7, 8, 13, 26, 35, 40,
70, 75. The given pre-order sequence is 35, 13, 7, 8, 26, 70, 40
and 75. So, the binary search tree formed is

Thus post-order sequence for the tree is 8, 7, 26, 13, 40, 75, 70 and 35.

Data Structures and Algorithms Unit – II Trees

You might also like