The document discusses topics related to trees and graphs. It covers definitions and concepts of trees, binary trees and their representations. It discusses operations on binary trees like tree traversals. Binary search trees and heap trees are also covered. The document also provides an introduction to graphs and discusses graph representations and traversals. It concludes with the topic of minimal spanning trees.
5. Trees
Definition:- Tree is a non linear data structures. It is a collection of
entities called nodes.
A tree is a finite set of one or more nodes such that:
i) There is a specially designated node called the root.
ii) Remaining nodes are partitioned into ‘n’(n>0) disjoint sets
T1,T2,..Tn, where each Ti (i=1,2,….n)is a Tree, T1,T2,..Tn are
called sub tree of the root.structure of a tree
A
B DC
E F G
K L
H I J
T1
T2
T3
S. Durga Devi , CSE, CBIT
6. Tree Terminology
Root: node without parent (A)
Siblings: nodes share the same parent
Internal node: node with at least one child
(A, B, C, F)
External node (leaf ): node without
children (E, I, J, K, G, H, D)
Ancestors of a node: parent, grandparent,
grand-grandparent, etc.
Descendant of a node: child, grandchild,
grand-grandchild, etc.
Level : set of nodes with same depth called
depth and root is termed as in level 0. If a
node is at level i and its child is at level i+1
and parent is at level i-1. This is true for all
except the root node.
Depth of a node: number of ancestors
Height of a tree: maximum depth of any
node (3)
Degree of a node: the number of its children
Degree of a tree: the maximum number of
its node.
Subtree: tree consisting of a node and its
descendants.
Sibling: node have same parent . I,J,K has
parent F.
A
B DC
G HE F
I J K subtree
S. Durga Devi , CSE, CBIT
7. • Path: a sequence of nodes and edges
connecting a node with descendants.
S. Durga Devi , CSE, CBIT
8. • Height of a tree:
• The height of tree is no of edges present in longest path of a tree
• A leaf node will have a height of 0.
• Height of a node is the number of edges on the longest path from the node
to a leaf.
•
S. Durga Devi , CSE, CBIT
Height of node A is 3 that is from
A->C->D->E
Not from A to G
9. • The depth of a node is the number of edges from root node to that particular node.
A root node will have a depth of 0.t
S. Durga Devi , CSE, CBIT
Note: depth and height of the tree
returns same value. But for individual
nodes gives different values.
10. - size:- size of a node is number of descendants and node itself. Node F size is 4.
- Skew trees: every node is a tree has exactly one child except the leaf node is called
skew tree.
- if every node has only left child is called left skew tree
- if every node has only right child is called right skew tree.
S. Durga Devi , CSE, CBIT
12. A tree satisfies the following properties:
1. It has one designated node, called the root, that has no
parent.
2. Every node, except the root, has exactly one parent.
3. A node may have zero or more children.
4. There is a unique directed path from the root to each node.
5
2
4 1 6
3
5
2
4 1 6
3
5
2
4
1
6
3
tree Not a tree Not a tree
13. Types of trees
1. Binary tree
2. Binary search tree
3. Heap tree
4. AVL- trees
5. Red-Black trees
6. Splay trees
7. B- Trees
S. Durga Devi , CSE, CBIT
14. Binary Trees
• Definition:-
A binary tree is a finite set of nodes such that
i. T is empty tree (called empty binary tree)
ii. T containsa specially designed nodecalled the root of T, and remaining
nodes of T form two disjoint binary trees T1 and T2 which are called left
sub tree and right sub tree respectively.
iii. Each nodein binary tree has at most two children. (0,1,2)
Example of binary tree Right sub tree
A
B C
D E
H I
F G
J
K
Left
sub tree
root
Right
sub
tree
left
sub
tree
15. • Difference between tree and binary tree
Trees
1.Tree never be empty
2. A node may have any no of
children nodes.
Binary tree
1. May be empty
2. A node may have
at most two children
0, 1, or 2
Two special situations of a binary tree are possible
1.Full binary tree
2.Complete binary tree.
3. Strict binary tree
S. Durga Devi , CSE, CBIT
16. Full binary tree
A binary tree is a full binary tree, if it contains maximum
possible number of nodes in all levels.
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
Level 0- 1node
Level 1-2nodes
Level 2-4 nodes
Level 3-8nodes
Complete binary tree
A binary tree is said to be complete binary tree, if all its levels have maximum
number of nodes except possibly the last level, and In the last level, the nodes
are attached starting from the left-most position. All leaf nodes at height h or h-
1.
1
2 3
4 5 6 7
8 9
Level 0-1node
Level 1-2 nodes
Level 2- 4 nodes
Level 3- 2 nodes
K
A
B C
D E
H I
F G
J
Not a CBTS. Durga Devi , CSE, CBIT
17. 3. strict binary tree:
every node in binary tree has exactly two
children except the leaf nodes.
S. Durga Devi , CSE, CBIT
A
B C
D E
H I
F G
18. Applications of trees
express trees used in compilers
Huffman code trees used in data compression
algorithms.
B- trees used in data bases.
S. Durga Devi , CSE, CBIT
19. 1. linearsequential representation (using arrays)
The nodes are stored level by level, starting from the zero level
where root node is present.
the following rules can be used to decide the location of any node of a
tree in the array.
a. The root node is at location 0.
b. If a node is at a location ‘i’, then its left child is located at 2 * i + 1
and right child is located at 2 * i + 2
c. The space required by an n node binary tree is 2n+1.
S. Durga Devi , CSE, CBIT
Binary tree representation
1. linearsequential representation
2. Linked list
20. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
A B D C . E G . . . . . F
Sequential representation
A
C
DB
F
E G
1
2
4
3
76
13
Example- linearsequential representation
S. Durga Devi , CSE, CBIT
21. Advantages of linear representation
1. Any nodecan be accessed from any other node by calculatingthe index
and this is efficient from execution point of view.
2. There is no overhead of maintaining the pointers.
3. Some programming languages like BASIC, FORTRAN, where dynamic
allocation is not possible, array representationis the only way to store a
tree.
disadvantages
1. Other than full binary tree, if u store any tree most of the memory
locationsare empty.
2. Allows only static representation. There is no possibleway to enhance
the size of the tree.
3. Inserting a new node and deletinga nodefrom it are inefficient with
this representation becausethese require considerabledata movement up
and down the array which demand excessive processing time.
S. Durga Devi , CSE, CBIT
22. struct node { /* a nodein the tree structure*/
struct node *lchild;
int data ;
struct node *rchild;
};
The pointer lchild stores the address of left child node.
The pointer rchild stores the address of right child node.
If child is not available NULL is stored.
A pointervariable root representsthe root of the tree.
Representation of Binary Tree using Linked List
The most popular way to present a binary tree.
Each element is represented by a node that has two link fields (leftChild
and rightChild)plusan element field.
The space required by an n node binary tree is n * sizeof a node.
S. Durga Devi , CSE, CBIT
23. +
- *
A B DC
200
300 400
500
600 700
100
200 500
300 400
600 700
S. Durga Devi , CSE, CBIT
24. python
Structure of a node of a tree
class createnode:
def __init__(self,key):
self.key=key
self.left=None
self.right=None
S. Durga Devi , CSE, CBIT
25. Binary tree insertion
1. Define structure for a node
• struct node
• {
• int data;
• struct node *left;
• struct node *right;
• };
2. Create new node
• struct node* createNode(int data)
• {
• // Allocate memory for new node
• struct node* node = (struct node*)malloc(sizeof(struct node));
•
• // Assign data to this node
• node->data = data;
•
• // Initialize left and right children as NULL
• node->left = NULL;
• node->right = NULL;
• return(node);
• }
S. Durga Devi , CSE, CBIT
26. int main()
{
// insert new node into a binary tree
struct node * root=createNode(20);
root->lchild=createNode(30);
root->rchild=createNode(40);
root->lchild->lchild=createNode(50);
root->rchild->lchild=creatNode(60);
return 0;
}
S. Durga Devi , CSE, CBIT
6050
4030
20
30. Post order traversal
void postorder(struct node *root)
{
if(root)
{
postorder(root->lchild);
postorder(root->rchild);
printf(“%d “, root->data);
}
}
S. Durga Devi , CSE, CBIT
31. write a python program to implement insertion and traversal operations on binary tree
S. Durga Devi , CSE, CBIT
32. Conversion of general tree to binary tree
S. Durga Devi , CSE, CBIT
Steps
1. Root node of the general tree will become
root node to Binary tree
2. Left most child in general tree will become left
child in binary tree
3. Left node siblings in general tree will become right child nodes
for the left node in binarty tree.
33. S. Durga Devi , CSE, CBIT
General Tree
A
B
I
H
E
F G
C
D
root
34. Properties of binary trees
1. In BT, the maximum number of nodes at level i, where i>=0
at level 0=20
=1 node
at level 1= 21=2 nodes
2. The maximum no of nodes possible in a binary tree of height h is
Nmax=2h+1-1
n= 2i
3. The minimum no of node possiblein a binary tree of height h is
Nmin=h+1
If height=2 maximum no of nodes are 7
If height =3 minimum no of nodes are 3
4. The minimum no of nodes possibleat every level is only one node.
When every parent node has on childsuch kind of tree is calledskew
binary tree.
Fig-b S. Durga Devi ,CSE,CBIT
35. 5. for any non empty binary tree, if n is the number of nodes and e is the
number of edges, then
n= e+1
6. for any non empty binary tree T, if n0 is the no. of leaf nodes and n2 is
the no. of internal nodes (degree-2), then
n0= n2+1
No of internal nodes n2 =3
No of leaf nodesn0 = 3+1=4
7. Minimum height of a binary tree with n number of nodes is
log2(n+1)
8. Total no of binary trees possible with n nodes is
(1/(n+1) )*2nCn
S. Durga Devi ,CSE,CBIT
36. • Total no of binary tree possible with 3 nodes is- 5- A,B,C
A
B C
1
A
B
C
2
A
B
C
3
A
B
C
4
A
B
C
5
Representation of binary tree
1. linearsequential representation (using arrays).
2. linked representation (using linked list)
S. Durga Devi ,CSE,CBIT
37. BinarayTree traversals
• This operationis used to visit each node in the tree exactly once.
• The tree can be traversed in various ways.
for a systematic traversal, it is betterto visit each node and its sub trees in the
same fashion.
• Followingare tree traversals
1. root, left, right- pre order
2. Left, root, right- In order
3. Left, right, root-post order
4. Level by level- level order
S. Durga Devi ,CSE,CBIT
38. Pre order traversal
1. Visit the root node.
2. Traverse the left sub- tree of root in preorder.
3. Traverse the right sub- tree of root in preorder.
In order traversal
1. Traverse the left sub tree of the root nodein in order.
2. visit the root node.
3.Traverse the right sub tree of the root nodein in order.
Postorder traversal
1.Traversethe left sub tree of the root nodein post order.
2. Traverse the right sub tree of the root nodein the post order.
3.Visit the root node.
Level order traversal
- visit the root first, then the roots left child, followed by roots right
child.
- we continuein this manner, visiting the nodes at each new level
from the leftmost node to the right most node.
S. Durga Devi ,CSE,CBIT
42. pre order of binary tree
A
B C
D E
H I
F G
J
K
Pre order- A,B,D,E,H,I,C,F,J,K,G
S. Durga Devi ,CSE,CBIT
43. In order of binary tree
A
B C
D E
H I
F G
J
K
Inorder- D,B,H,E,I,A,F,K,J,C,G
S. Durga Devi ,CSE,CBIT
44. In order of binary tree
A
B C
D E
H I
F G
J
K
Inorder- D,B,H,E,I,A,F,K,J,C,G
S. Durga Devi ,CSE,CBIT
45. Post order of binary tree
A
B C
D E
H I
F G
J
K
Post order- D,H,I,E,B,K,J,F,G,C,A
S. Durga Devi ,CSE,CBIT
46. Level order of binary tree
A
B C
D E
H I
F G
J
K
Level order- A,B,C,D,E,F,G,H,I,J,K
S. Durga Devi ,CSE,CBIT
47. Write pre,in and post order of the following tree
• (A-B) + C* (D/E)
+
- *
A B C /
D E
S. Durga Devi ,CSE,CBIT
48. Pre order for the following tree
+
- *
A B C /
D E
Pre order- +,-,A,B,*,C,/,D,E.
S. Durga Devi ,CSE,CBIT
49. in order of the following tree
+
- *
A B C /
D E
Pre order- +,-,A,B,*,C,/,D,E.
In order- A,-,B,+,C,*,D,/,E
50. post order of the following tree
+
- *
A B C /
D E
Pre order- +,-,A,B,*,C,/,D,E.
In order-A,-,B,+,C,*,D,/,E
51. Binary search tree
Binary search tree is one type of binary tree.
Binary search tree is a binary tree that may be empty .
Non empty binary search tree satisfies the following properties.
1. every nodehas a value and no two elements (node)have same value,
therefore all values are different.
2. The values in the left sub tree are smaller than value of its root node.
3. The values in the right sub tree are greater than its value of the root node.
4. The left and right sub tree of the root also binary search tree.
k
All<K All>K
S. Durga Devi , CSE, CBIT
52. • The following are the bst( binary search trees)
18
15 20
12 17 25
35
45
5040
20
15 25
12 18 22
Its not a binary search
tree because it fails to satisfy
the property of 3 and 4
S. Durga Devi , CSE, CBIT
53. Binary search tree representation
• Binary search tree representation is same as
binary tree representation
• Refer binary tree representation.
S. Durga Devi ,CSE,CBIT
55. 1. Search operation on BST
• Searching-
supposewe wish to search an element with key or value (K), we begin at the
root. If root is NULL, the search tree contains no such element, the search
is unsuccessful.
• Otherwise, we compare key value with value of root node. if K < key
value in the root, then no element in the right sub tree and only left sub tree
is to be searched.
• If K is greater than key in the root, only the right sub tree is to be searched.
• This process repeated until the key element is found or reached to the leaf
nodes.
• If K= key value in the root, then search terminates successfully. The sub
tree may be searched similarly.
S. Durga Devi ,CSE,CBIT
56. Example- find a given key node in a following BST
20
15
25
12
18 22
Search node-22
22>20
S. Durga Devi ,CSE,CBIT
57. Insertion operation on BST
• Insertion operation on a binary search tree is very simple. In fact, one step
more than the searching operation.
• To insert a nodewith data, say ITEM, into a tree, the tree is to be searched
starting from the root node.
• If ITEM is found, do nothing, otherwise ITEM is to be inserted at the dead
end where search halts.
6
2 8
1 4
3
a) Before insertion
Insert node- 5
6
2
1 4
3 5
8
b) After inserting node 5
S. Durga Devi , CSE, CBIT
58. Construct BST with following elements
19, 55,44,98,8,23,15,6,10,82,99
19
55
98
99
23
44
82
8
6 15
10
Root
S. Durga Devi ,CSE,CBIT
59. Deletion operation on BST
• Anotherfrequentlyused operation on the BST is to deleteany node from it.
This is slightly complicated one.
• To delete a node from a binary search tree, there are three possible cases
when we deletea node.
case-1-if deleted nodeis a leaf nodeor node has no children, it can be deleted
by making its parent pointers( left, right) to NULL.
30
25 40
20
35 45
30
25 40
20 45
a. Before deletion
b. After deletionDeleted node-35
S. Durga Devi ,CSE,CBIT
60. Case-2 if the deleted node has one child, either left child or
right child, its parent pointer needs to be changed.
4
6
8
9
7
After deletion
8
6
7
9
4
1
Deleted
node-1
S. Durga Devi ,CSE,CBIT
63. case-3
• If deleted nodehas two children
• First find out the inorder successor (X) of the deleted node( in order
successor means the node which comes after the deleted nodeduring the
inorder traversal).
• Delete a node X from tree by using case 1 or case 2 (it can be verified that
x never has a left child) and then replacethe data content in deleted node
by the data of the x.
45
35
27
24
2916
20 45
2916
24
35
42 42
3327
x 33
S. Durga Devi
,CSE,CBIT
64. Merge or join BST
• Another interesting operations on BST are
recombine them (merge) and split BST in
interesting ways.
• Merge: Combine two Binary search trees into
single binary search tree.
• Split: break binary search tree into two binary
search trees.
S. Durga Devi ,CSE,CBIT
65. • Write a program to implement BST with
following operations
i insertion ii deletion iii inorder iv postorder v
preorder.
S. Durga Devi ,CSE,CBIT
73. Height of a Binary Tree
- Get height of the left sub tree say it hl
- Get height of the right sub tree say it hr.
- Take the Maxheight(leftHeight, rightHeight) and add 1 for the root and
return.
- Call recursively.
int Findheight(root)
{
if (root==NULL)
return -1
Leftheight = Findheight(root->left);
Rightheight= Findheight(root->right);
Return max(Leftheight, Rightheight)+1;
}
S. Durga Devi ,CSE,CBIT
74. Copying a binary tree
• In postorder, the root is visited last
• Here’s a postorder traversal to make a complete copy of a
given binary tree:
• node *copy( root ) :
• if (root == NULL ) : return -1;
• //create new node and make it a copy of node pointed by root
• node *temp = (node *)malloc(sizeof(node)) ;
• temp->data = root-> data; //copying data
• temp->left = copy(root -> left); //cloning left child
• temp->right = copy(root -> right); //cloning right child
• return temp;
S. Durga Devi ,CSE,CBIT
75. Advantages of linked representation
This representation is superior to the array representation as there is no
wastage of memory.
There is no need to have prior knowledge of depth of the tree. Using dynamic
memory allocation concept one can create as much memory (node) as
required.
Insertion and deletion which are the most common operations can be done
without moving the other nodes.
Disadvantages of linked representation
This representation does not provide direct access to a node.
It needs additionalspace in each nodefor storing the left and right subtrees.
S. Durga Devi ,CSE,CBIT
76. Threaded binary tree
• In linked list representation thereare more null links than actual pointers. If
there are n nodes n+1 null links are present and total links are 2n.
• To make use of these null pointersthreaded binary trees are introduced.
Definition
• A binary tree is said to be threadedbinary tree by making all right child
pointersthat would normally be null point to the inorder successor of the node,
and all the left child pointers that would normally be null point to the inorder
predecessorof the node.
Advantages
• Inorder traversal can be donefaster without using stack.
• Makes use of null pointersin binary tree.
• Successor and predecessor can be find easily.
S. Durga Devi ,CSE,CBIT
78. Threaded Binary Tree
• Threads are two types
1. One way threaded binary tree
2. Two way threaded binary tree
1. Threaded Binary Tree One-Way
• Accordingly, in the one way threading of T, a thread will appear
in the right field of a node and will point to the next node in the
in-order traversal of T.
• See the bellow example of one-way in-order threading.
S. Durga Devi ,CSE,CBIT
80. 2. Threaded Binary Tree Two-Way
• In the two-way threading of T.
• A thread will also appear in the left field of a node and
will point to the preceding node in the in-order traversal
of tree T.
• Furthermore, the left pointer of the first node and the
right pointer of the last node (in the in-order traversal of
T) will contain the null value when T does not have a
header node.
S. Durga Devi ,CSE,CBIT
81. Threaded Binary Tree
• Bellow figure show two-way in-order threading.
• Here, right pointer=next node of in-order traversal and
left pointer=previous node of in-order traversal
• Inorder of bellow tree is: D,B,F,E,A,G,C,L,J,H,K
S. Durga Devi ,CSE,CBIT
83. Memory representation of threaded binary tree
• In memory representation we must be able to distinguish between thread and
normal pointers.
• Node structure represented with two additional boolean fields left thread and
right thread to tree node.
• If tree→leftthread==TRUE, then tree→leftchild contains a thread; otherwise, it
contains false value. Similarly, if tree→rightthread == TRUE,
then tree→rightchild contains a thread. Otherwise it contains a false value.
Lefthtread Left child Data Right child Right
thread
S. Durga Devi ,CSE,CBIT
85. Threaded Binary Tree
Two-way Threading with Header node
• Again two-way threading has left pointer of the first
node and right pointer of the last node (in the inorder
traversal of T) will contain the null value when T will
point to the header nodes is called two-way threading
with header node threaded binary tree.
S. Durga Devi ,CSE,CBIT
86. Threaded Binary Tree
• Bellow figure to explain two-way threading with header node.
S. Durga Devi ,CSE,CBIT
87. Threaded Binary Tree
• Bellow example of link representation of threading
binary tree.
• In-order traversal of bellow tree: G,F,B,A,D,C,E
S. Durga Devi ,CSE,CBIT
89. Priority queue ADT
• Priority queueis abstract data type which is like a queue or stack data
structurebut each element has been assigned a value called priority of the
element, and an element can be inserted or deleted not only at the ends but
at any position in the queue.
• Some contexts where some things should be allowed to skip ahead in the
line?
• Applications
- Lower berths of a train during reservation are allocated first to the old age
persons. Here priority is age of a person.
- In operatingsystem runnable processes might be stored in priority queue,
where certain system processes are given a higher priority than user
processes.
- In networks packets of data routed according to some assigned priorities.
S. Durga Devi ,CSE,CBIT
90. Heaps
• Priority queues are implemented using heaps.
• Heaps are in form of binary tree structure.
• Definition of binary heap:
- heap tree must be complete binary tree
There are two types of binary heaps
1. Max Heap Tree: Max heap is a tree in which the value in each
node is greater than or equal to its children.
2. Min Heap Tree: Min heap is a tree in which the value in each
node is smaller than or equal to its children.
S. Durga Devi ,CSE,CBIT
92. Binary Heaps: Array Implementation
• Heap trees are implemented either in linked list or
array.
• Array representation have more advantages over the
linked list because heap tree is a complete binary tree.
So there is no wastage of memory.
• Elements of heap are stored in an array level by level.
S. Durga Devi ,CSE,CBIT
94. Insertion into a heap tree
• Insertion into a heap must maintain both the complete binary tree structure
and the heap order property. To do this what we do is the following.
• We know that in order to maintain the complete binary tree structure, we
must add a node to the first open spot at the bottom level. So we begin by
adding a node without data there. After that what we do is we see if
inserting our new value will violate the heap property. If it doesn't put it in
and we are done. Otherwise, we move the value from the parent of the
empty node down , thus creating an empty node where the parent use to
be. We again check to see if inserting the value violates the heap order
property. If not, we add it in. Otherwise repeat the process until we are
able to add the value. This process of moving the empty node towards the
root is called percolate up
S. Durga Devi ,CSE,CBIT
95. Example
• Construct a min heap with following
elements:10,6,20,5, 16, 17, 13,2
10
Insert 10
S. Durga Devi ,CSE,CBIT
111. 2Insert 2
5
2<5 then swap
13
6
16 20 17
10
This process of moving the empty node
towards the root is called percolate up
S. Durga Devi ,CSE,CBIT
112. Heap tree deletion
Deletion process for min heap tree
1. Remove root (that is always the min!)
2. Replace root node with “last” leaf node in the heap
tree.
3. Find smallest child of node
4. Swap node with its smallest child if needed.
5. Repeat steps 3 & 4 until no swaps needed.
6. Tree must satisfy the properties of heap tree.
This process of moving the empty node towards the child is called percolate
down
S. Durga Devi ,CSE,CBIT
115. Heap sort
• There are two main applications of heap tree
1. sorting data ( heap sort)
2. implement priority queue.
Heap sort:
to sort the data in ascending(Descending)
order, build max heap (min heap) .
S. Durga Devi ,CSE,CBIT
117. Why study Heapsort?
• It is a well-known, traditional sorting
algorithm you will be expected to know
• Heapsort is always O(n log n)
– Quicksort is usually O(n log n) but in the worst
case slow down to O(n2)
– Quicksort is generally faster, but Heapsort is better
in time-critical applications
• Heapsort is a really cool algorithm!
S. Durga Devi ,CSE,CBIT
118. Heap sort
• Algorithm
1. Build a tree with the given data
2. a) delete root node from the heap
b) rebuild the heap tree after the deletion.
c) place the deleted node in the output array.
3. Continue step 2 until the heap tree is empty.
Note: To sort the data in ascending( descending)
construct max(min) heap in the step 1
S. Durga Devi ,CSE,CBIT
119. Mapping into an array
19
1418
22
321
14
119
15
25
1723
25 23 17 19 22 14 15 18 14 21 3 9 11
0 1 2 3 4 5 6 7 8 9 10 11 12
• Notice:
– The left child of index i is at index 2*i+1
– The right child of index i is at index 2*i+2
– Example: the children of node 3 (19) are 7 (18) and 8 (14)
S. Durga Devi ,CSE,CBIT