Trees
Trees
com
1
byjusexamprep.com
5 TREES
1. TREES
• A tree is a non-linear data structure designated at a special node called the root and
elements are arranged in levels without containing cycles.
• All the elements are arranged in layers.
• A unique path traverses from root to any node of the tree.
• Every child has only one parent, but the parent can have many children.
• If a tree has N vertices(nodes) then the number of edges is always one less than the number
of nodes(vertices) i.e N-1. If it has more than N-1 edges it is called a graph not a tree.
2
byjusexamprep.com
• Binary tree partitioned into three parts.
• First subset contains root of tree
• Second subset is called left subtree
• Another subset is called right subtree
• Each subtree is a binary tree.
• Degree of any node is 0/1/2.
• The maximum number of nodes in a tree with height ‘h’ is 2 h+1 – 1.
• The maximum number of nodes at level ‘i’ is 2i-1.
• For any non-empty binary tree, the number of terminal nodes with n 2, nodes of degree
2 is N0 = n2 + 1
• The maximum number of nodes in a tree with depth d is 2d-1.
• Time Complexities:
Insertion: O(n) {Every Case}
Deletion: O(n) {Every Case}
1.1.2. Types of Binary Trees:
3
byjusexamprep.com
a. Full Binary Tree
• If each node of binary tree has either two children or no child at all, is said to be
a Full Binary Tree.
• Full binary tree is also called as Strictly Binary Tree.
• In a complete binary tree, every internal node has exactly two children and all leaf
nodes are at the same level.
• For example, at Level 2, there must be 2 2 = 4 nodes and at Level 3 there must be 2 3 =
8 nodes.
c. Skewed Binary Tree
• If a tree which is dominated by left child node or right child node, is said to be
a Skewed Binary Tree.
4
byjusexamprep.com
• In a skewed binary tree, all nodes except one have only one child node. The remaining
node has no child.
• In a left skewed tree, most of the nodes have the left child without corresponding right
child.
• In a right skewed tree, most of the nodes have the right child without corresponding
left child.
d. Strict Binary Tree:
• If every non-leaf node in a binary tree has nonempty left and right subtrees, the tree
is called a strict binary tree.
• A strict binary tree with n leaves always contains 2n -1 nodes.
• If every non-leaf node in a binary tree has nonempty left and right subtrees,
the tree is termed a strict binary tree. Or, to put it another way, all of the nodes in
a strict binary tree are of degree zero or two, never degree one.
e. Rooted Binary Tree:
A rooted binary tree is a binary tree in which only the root is allowed to have degree 2.
The remaining nodes have degrees equal to either 1 or 3.
5
byjusexamprep.com
6
byjusexamprep.com
1.2.2. In-order : (L, V, R)
• Traverse the left-subtree in in-order
• Visit Root of the tree
• Traverse right-subtree in in-order
1.2.3. Post-order : (L, R, V)
• Traverse the left subtree in post-order
• Traverse the Right-subtree in post-order
• Visit root of the tree
Example 1 :
Pre-order : A B D F E C G I H J
In-order : F D B E A G I C H J
Post-order : F D E B I G J H C A
Pre-order, In-order and post-order uniquely identify the tree.
1.3. OPERATIONS ON BINARY SEARCH TREE
1.3.1. BST Insertion:
Insert function is used to add a new element in a binary search tree at appropriate
location. Insert function is to be designed in such a way that it must not violate the
property of binary search tree at each value.
1. Allocate the memory for tree.
2. Set the data part to the value and set the left and right pointer of the tree, pointing to
NULL.
3. If the item to be inserted, will be the first element of the tree, then the left and right
of this node will point to NULL.
4. Else, check if the item is less than the root element of the tree, if this is true, then
recursively perform this operation with the left of the root.
5. If this is false, then perform this operation recursively with the right subtree of the
root.
7
byjusexamprep.com
Example 2: Insert 43, 10, 79, 90, 12, 54, 11, 9, 50 in a BST.
1. Insert 43 into the tree as the root of the tree.
2. Read the next element, if it is less than the root node element, insert it as the root of
the left sub-tree.
3. Otherwise, insert it as the root of the right of the right subtree.
The process of creating BST by using the given elements, is shown in the image below.
8
byjusexamprep.com
Here node 85 is deleted, since the node is a leaf node, therefore the node will be replaced
with NULL and allocated space will be freed.
9
byjusexamprep.com
Example 3: Which of the following list of nodes corresponds to post order traversal of
the binary tree shown below?
(A) A B C D E F G H I J
(B) J I H G F E D C B A
(C) D H E B I F J G C A
(D) D E H F I G J B C A
Sol: The correct option is C as in post order traversal we follow left child, right child, root.
Hence DHEBIFJGCA.
Example 4: A binary search tree is generated by inserting in order the following integers:
55, 15, 65, 5, 25, 59, 90, 2, 7, 35, 60, 23
The number of nodes in the left subtree and right subtree of the root respectively are
(A) 8, 3
(B) 7, 4
(C) 3, 8
(D) 4, 7
Ans. 55, 15, 65, 5, 25, 59, 90, 2, 7, 35, 60, 23
10
byjusexamprep.com
Here 55 is the root node so, all the elements smaller than 55 will go on the left of all the
elements greater than 55 will go on the RHS.
Hence, option B is correct
Example 5: How many distinct binary search trees can be constructed out of 4
distinct keys?
a.14
b.24
c.35
d.5
Solution-
Number of distinct binary search trees possible with 4 distinct keys
= 2n
Cn / n+1
= 2×4
C4 / 4+1
= 8C4 / 5
= 14
Thus, Option (A) is correct.
Example 6: Consider we want to draw all the binary trees possible with 3
unlabelled nodes.
Sol: Number of binary trees possible with 3 unlabelled nodes
= 2x3
C3 / (3 + 1)
= 6C3 / 4
=5
1.4 HEAPS
• Heap is a special case of balanced binary tree data structure where the root-node key
is compared with its children and arranged accordingly.
• Heaps also have an additional property that all leaves should be at h or h-1 levels,
where h is the height of the tree.
Min-Heap − Where the value of the root node is less than or equal to either of its
children. The same property must be true for all subtrees.
11
byjusexamprep.com
Max-Heap − Where the value of the root node is greater than or equal to either of its
children. The same property must be true for all subtrees.
10 14 19 26 31 42 27 10 26 14
12
byjusexamprep.com
In max-heap, to heapify an element, find the maximum of its children and swap it with
the current element and continue this process until the heap property is satisfied at every
node.
One important property of heap is that, if an element is not satisfying the heap property
then all the elements from that element to root will also have the same problem.
In below example, element 1 is not satisfying the heap property and its parent 31 is also
having the issue. Similarly, if we heapify an element then all the elements from that
element to root will also satisfy the heap property automatically.
In the above heap, the element 1 is not satisfying the heap property so, heapifying this
element.
To heapify 1, find the maximum of its children and swap with that.
Continue this process until the element satisfies the heap properties. Now, swap 1 with
8.
13
byjusexamprep.com
1.4.3. Inserting an Element:
Insertion of an element is very much similar to the heapify and deletion process.
Increase the heap size
Keep the new element at the end of the heap (tree)
Heapify the element from bottom to top (root)
Here inserting the element 19 at the end of the heap, the heap property is not satisfied.
In-order to heapify this element (19), compare it with its parent and adjust them.
Swapping 19 and 14 gives :
14
byjusexamprep.com
1.4.4. Deleting an Element:
Deleting an element at any intermediary position in the heap can be costly, so replace
the element to be deleted by the last element and delete the last element of the Heap.
• Replace the root or element to be deleted by the last element.
• Delete the last element from the Heap.
• Since, the last element is placed at the position of the root node. So, it may not follow
the heap property. Therefore, heapify the last node placed at the position of root.
Example 7 : Suppose the Heap is a Max-Heap as:
15
byjusexamprep.com
• The above tree is an AVL tree because the difference between heights of left and right
subtrees for every node is less than or equal to 1.
• The above tree is not AVL because the difference between heights of left and right
subtrees for 9 and 19 is greater than 1.
• It checks the height of the left and right subtree and assures that the difference is not
more than 1. The difference is called the balance factor.
• Time Complexities:
Insertion: O(logn)
Deletion: O(logn)
i. Left Rotation
If a tree becomes unbalanced, when a node is inserted into the right subtree of the right
subtree, then we perform a single left rotation −
16
byjusexamprep.com
Here, node A has become unbalanced as a node is inserted in the right subtree of A's
right subtree. Hence, left rotation is performed by making A the left-subtree of B.
ii.Right Rotation
AVL tree may become unbalanced, if a node is inserted in the left subtree of the left
subtree. The tree then needs a right rotation.
Here, the unbalanced node becomes the right child of its left child by performing a right
rotation.
17
byjusexamprep.com
iii.Left-Right Rotation
A left-right rotation is a combination of left rotation followed by right rotation.
State Action
A node has been inserted into the right subtree of the left subtree. This
makes C an unbalanced node. These scenarios cause AVL tree to
perform left-right rotation.
first perform the left rotation on the left subtree of C. This makes A,
the left subtree of B.
Now right-rotate the tree, making B the new root node of this
subtree. C now becomes the right subtree of its own left subtree.
18
byjusexamprep.com
iv. Right-Left Rotation
The second type of double rotation is Right-Left Rotation. It is a combination of right
rotation followed by left rotation.
State Action
A node has been inserted into the left subtree of the right subtree.
This makes A, an unbalanced node with balance factor 2.
First, perform the right rotation along C node, making C the right
subtree of its own left subtree B. Now, B becomes the right subtree
of A.
19
byjusexamprep.com
Example 8 : Construct an AVL tree by inserting the following elements in the
given order.
63, 9, 19, 27, 18, 108, 99, 81
• At each step,the balance factor for every node is calculated.
• If it is found to be other than -1,0,1 then we need a rotation to rebalance the tree.
• The type of rotation will be estimated by the location of the inserted element with
respect to the critical node.
All the elements are inserted in order to maintain the order of the binary search tree.
b.Deletion:
Delete(T,k) means delete a node with the key k from the AVL tree T.
I) Find the node x where k is stored
II) Delete the contents of node x
There are three possible cases:
1) If x has no children (i.e., is a leaf), delete x.
2) If x has one child, let x' be the child of x.
20
byjusexamprep.com
Notice: x' cannot have a child, since subtrees of T can differ in
height by at most one
-replace the contents of x with the contents of x'
-delete x' (a leaf)
3) If x has two children,
-find x's successor z (which has no left child)
-replace x's contents with z's contents, and
-delete z.
[since z has at most one child, so we use case (1) or (2) to delete z]
III) Third: Go from the deleted leaf towards the
root and at each ancestor of that leaf:
-update the balance factor
-rebalance with rotations if necessary.
Example 9 : Delete the node 30 from the AVL tree shown in the following image.
Sol: In this case, the node B has balance factor 0, therefore the tree will be rotated by
using R0 rotation as shown in the following image. The node B(10) becomes the root,
while the node A is moved to its right. The right child of node B will now become the left
child of node A.
1.6. B- TREE
• B Tree is a specialized m-way tree that can be widely used for disk access.
• A B-Tree of order m can have at most m-1 keys and m children.
• One of the main reasons for using B tree is its capability to store a large number of
keys in a single node and large key values by keeping the height of the tree relatively
small.
21
byjusexamprep.com
• Time Complexities:
Insertion: O(logn)
Deletion: O(logn)
1.7. B+ TREE
• B+ Tree is an extension of B Tree which allows efficient insertion, deletion and search
operations.
• In B Tree, Keys and records both can be stored in the internal as well as leaf nodes.
Whereas, in B+ tree, records (data) can only be stored on the leaf nodes while internal
nodes can only store the key values.
• The leaf nodes of a B+ tree are linked together in the form of singly linked lists to
make the search queries more efficient.
• Time Complexities:
Insertion: O(logn)
Deletion: O(logn)
Example 10 : Construct minimal AVL trees of height 0, 1, 2, 3, and 4. What is the number
of nodes in a minimal AVL tree of height 5?
Sol. Let n(h) be the number of nodes in a minimal AVL tree with height h.
N(0) = 1
N(1) = 2
22
byjusexamprep.com
N(h) = 1 + N (h – 1) + N(h – 2)
23
byjusexamprep.com
2. Graphs
• A graph is a pictorial representation of a set of objects where some pairs of objects are
connected by links. The interconnected objects are represented by points termed
as vertices, and the links that connect the vertices are called edges.
Formally, a graph is a pair of sets (V, E), where V is the set of vertices and E is the set of
edges, connecting the pairs of vertices. Take a look at the following graph −
24
byjusexamprep.com
Basic Operations
Following are basic primary operations of a Graph −
● Add Vertex − Adds a vertex to the graph.
● Add Edge − Adds an edge between the two vertices of the graph.
● Display Vertex − Displays a vertex of the graph.
2.1 Types of Graphs
2.1.1 Null Graph
A graph having no edges is called a Null Graph.
Example
In the above graph, there are three vertices named ‘a’, ‘b’, and ‘c’, but there are no
edges among them. Hence it is a Null Graph.
2.1.2. Trivial Graph
A graph with only one vertex is called a Trivial Graph.
Example
In the above shown graph, there is only one vertex ‘a’ with no other edges. Hence it is
a Trivial graph.
25
byjusexamprep.com
2.1.3 Non-Directed Graph
A non-directed graph contains edges but the edges are not directed ones.
Example
In this graph, ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’ are the vertices, and ‘ab’, ‘bc’, ‘cd’, ‘da’, ‘ag’, ‘gf’,
‘ef’ are the edges of the graph. Since it is a non-directed graph, the edges ‘ab’ and ‘ba’
are the same. Similarly other edges are also considered in the same way.
2.1.4 Directed Graph
In a directed graph, each edge has a direction.
Example
In the above graph, we have seven vertices ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, and ‘g’, and eight
edges ‘ab’, ‘cb’, ‘dc’, ‘ad’, ‘ec’, ‘fe’, ‘gf’, and ‘ga’. As it is a directed graph, each edge
bears an arrow mark that shows its direction. Note that in a directed graph, ‘ab’ is
different from ‘ba’.
26
byjusexamprep.com
2.1.5 Simple Graph
A graph with no loops and no parallel edges is called a simple graph.
● The maximum number of edges possible in a single graph with ‘n’ vertices
is nC2 where nC2 = n(n – 1)/2.
● The number of simple graphs possible with ‘n’ vertices = 2nc2 = 2n(n-1)/2.
Example
In the following graph, there are 3 vertices with 3 edges which is maximum excluding
the parallel edges and loops. This can be proved by using the above formulae.
27
byjusexamprep.com
2.1.6 Connected Graph
A graph G is said to be connected if there exists a path between every pair of
vertices. There should be at least one edge for every vertex in the graph. So that we
can say that it is connected to some other vertex at the other side of the edge.
Example
In the following graph, each vertex has its own edge connected to another edge. Hence
it is a connected graph.
The two components are independent and not connected to each other. Hence it is
called disconnected graph.
Example 2
28
byjusexamprep.com
In this example, there are two independent components, a-b-f-e and c-d, which are not
connected to each other. Hence this is a disconnected graph.
2.1.8 Regular Graph
A graph G is said to be regular, if all its vertices have the same degree. In a graph,
if the degree of each vertex is ‘k’, then the graph is called a ‘k-regular graph’.
Example
In the following graphs, all the vertices have the same degree. So these graphs are
called regular graphs.
In both the graphs, all the vertices have degree 2. They are called 2-Regular Graphs.
Complete Graph
A simple graph with ‘n’ mutual vertices is called a complete graph and it is denoted by
‘Kn’. In the graph, a vertex should have edges with all other vertices, then it
called a complete graph.
In other words, if a vertex is connected to all other vertices in a graph, then it is called
a complete graph.
Example
In the following graphs, each vertex in the graph is connected with all the remaining
vertices in the graph except by itself.
29
byjusexamprep.com
Example
Take a look at the following graphs −
● Graph I has 3 vertices with 3 edges which form a cycle ‘ab-bc-ca’.
● Graph II has 4 vertices with 4 edges which form a cycle ‘pq-qs-sr-rp’.
● Graph III has 5 vertices with 5 edges which form a cycle ‘ik-km-ml-lj-ji’.
3. Graph Traversal
Graph traversal is a technique used for a searching vertex in a graph. The graph traversal is
also used to decide the order of vertices visited in the search process. A graph traversal finds
the edges to be used in the search process without creating loops. That means using graph
traversal we visit all the vertices of the graph without getting into a looping path.
There are two graph traversal techniques and they are as follows.
3.1. DFS (Depth First Search)
3.2. BFS (Breadth First Search)
30
byjusexamprep.com
● Step 5 - When there is no new vertex to visit then use backtracking and pop one
vertex from the stack.
● Step 6 - Repeat steps 3, 4 and 5 until stack becomes Empty.
● Step 7 - When stack becomes Empty, then produce final spanning tree by removing
unused edges from the graph.
Depth First Search (DFS) algorithm traverses a graph in a depthward motion and uses a
stack to remember to get the next vertex to start a search, when a dead end occurs in
any iteration.
31
byjusexamprep.com
32
byjusexamprep.com
As C does not have any unvisited adjacent node so we keep popping the stack until we
find a node that has an unvisited adjacent node. In this case, there's none and we keep
popping until the stack is empty.
3.2. Breadth first Search
Breadth First Search (BFS) algorithm traverses a graph in a breadthward motion and
uses a queue to remember to get the next vertex to start a search, when a dead end
occurs in any iteration.
33
byjusexamprep.com
As in the example given above, the BFS algorithm traverses from A to B to E to F first
then to C and G lastly to D. It employs the following rules.
● Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in
a queue.
● Rule 2 − If no adjacent vertex is found, remove the first vertex from the queue.
● Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.
34
byjusexamprep.com
35
byjusexamprep.com
At this stage, we are left with no unmarked (unvisited) nodes. But as per the algorithm
we keep on dequeuing in order to get all unvisited nodes. When the queue gets
emptied, the program is over.
3.3. Difference between DFT and BFT
BFT DFT
BFS stands for Breadth First Search. DFS stands for Depth First Search.
BFS(Breadth First Search) uses Queue DFS(Depth First Search) uses Stack
data structure for finding the shortest data structure.
path.
BFS can be used to find a single source In DFS, we might traverse through more
shortest path in an unweighted graph, edges to reach a destination vertex from
because in BFS, we reach a vertex with a source.
minimum number of edges from a
source vertex.
BFS is more suitable for searching DFS is more suitable when there are
vertices which are closer to the given solutions away from source.
source.
BFS considers all neighbours first and DFS is more suitable for game or puzzle
therefore not suitable for decision problems. We make a decision, then
making trees used in games or puzzles. explore all paths through this decision.
And if this decision leads to a win-win
situation, we stop.
The Time complexity of BFS is O(V + E) The Time complexity of DFS is also O(V
when Adjacency List is used and O(V^2) + E) when Adjacency List is used and
when Adjacency Matrix is used, where V O(V^2) when Adjacency Matrix is used,
stands for vertices and E stands for where V stands for vertices and E stands
edges. for edges.
****
36