BINARYTREE
Abinarytreeisafinitesetofelementsthatiseitheremptyoris
partitionedintothreedisjointsubsets.
-Thefirstsubsetcontainsasingleelementcalledtherootofthe
tree.
-Theothertwosubsetsarethemselvesbinarytrees,calledtheleft
andrightsubtreesoftheoriginaltree.Aleftorrightsubtreecanbe
empty.Eachelementofatreeiscalledanodeofthetree.
B
G
E
D
IH
F
c
A Binary tree
8
STRUCTURESTHATARENOTBINARYTREES
9
TYPESOFBINARYTREE
1.Strictly binary trees
2.Complete binary tree
3.Extended binary tree
10
STRICTLYBINARYTREES
•Ifeverynon-leafnodeinabinarytreemusthavetwosubtree
leftandrightsub-trees,thetreeiscalledastrictlybinarytree.
•Astrictlybinarytreewithnleavesalwayscontains2n-1
nodes.
•Here, B,E,F,G are leaf nodes. So n=4, No. of nodes=2*4-1=7
B
D
G
F
E
C
A
11
COMPLETEBINARYTREE
Thetreeissaidtobecompletebinarytreeifallitslevels,except
possiblythelast,havethemaximumnumberofpossiblenodes
andifallthenodesatlastlevelappearasfarleftaspossible.
Maximumnumberofnodesatanylevelr=2
r
Eq:-atlevel0maximumnumberofnodes=2º=1
Atlevel2maximumnumberofnodes=2²=4andsoon.
.
12
Linked Representation
struct node {
int info;
struct node *left;
struct node *right;
};
infoleft right
info
left right
23
LINKEDREPRESENTATION
ROOT
A
B x C x
x D x E x
x F x
24
LINKEDREPRESENTATION
1
2
3
4
5
6
7
8
9
10
B
C
D
E
A 3
6
8 9
X
X
X
7
X
X
1ROOT
F
4
5
X X
2AVAIL
25
TRAVERSINGABINARYTREE
Three methods:
1. inorder
2. preorder
3. postorder
Preorder
1. Visit the root
2. Traverse the left subtree in preorder
3. Traverse the right subtree in preorder
Root-left-right93
4
14
18
15
20
7
16
17
5
Postorder
1. Traverse the left subtree in postorder
2. Traverse the right subtree in postorder
3. Visit the root
Left-right-root
Inorder
1. Traverse the left subtree in inorder
2. Visit the root
3. Traverse the right subtree in inorder
Left-root-right
26
27
TRAVERSINGABINARYTREE
Preorder
1. Visit the root
2. Traverse the left subtree in preorder
3. Traverse the right subtree in preorder
preorder: ABDGCEHIF
Postorder
1. Traverse the left subtree in postorder
2. Traverse the right subtree in postorder
3. Visit the root
postorder: GDBHIEFCA
D
B
A
F
C
E
G
IH
Inorder
1. Traverse the left subtree in inorder
2. Visit the root
3. Traverse the right subtree in inorder
inorder: DGBAHEICF
28
TRAVERSINGABINARYTREE
Preorder
1. Visit the root
2. Traverse the left subtree in preorder
3. Traverse the right subtree in preorder
preorder: ABCEIFJDGHKL
Inorder
1. Traverse the left subtree in inorder
2. Visit the root
3. Traverse the right subtree in inorder
inorder: EICFJBGDKHLA
Postorder
1. Traverse the left subtree in postorder
2. Traverse the right subtree in postorder
3. Visit the root
postorder: IEJFCGKLHDBA
C
B
A
L
H
D
K
G
E
I
F
J
29
APPLY EACH TRAVERSAL IN BINARY
TREE
30
PREORDER: ABDCEFG
INORDER: BDAECGF
POSTORDER: DBEGFCA
TRAVERSING
There are two solution for traversing
•Recursive
•Non-recursive
31
INORDERTRAVERSAL
1) Create an empty stack S.
2) Initialize current node as root
3) Push the current node to S and
set current =current->left until current is NULL
4) If current is NULL and stack is not empty then
a) Pop the top item from stack.
b) Print the popped item, set current = current->right
c) Go to step 3.
5) If current is NULL and stack is empty then we are done.
37
Innonrecursivetraversing,stackisusedtostorethenodeswhichhasto
bevisitedlater.
1.SetTop:=0
2.P=Root.
3.Repeatstep4to10while(P≠NULL)
4.RepeatSteps5to6while(P≠NULL)
5.Push(Stack,P)
6.P=Left[P]
[EndofStep4whileloop.]
7. IF(Stack is non empty)
8. P=Pop(Stack)
9. Print P
10. P=Right[P]
[End of If structure.]
[End of Step 3 while loop.]
11.Stop
INORDERTRAVERSAL
struct node {
int info;
struct node *left;
struct node *right;
};
38
CONSTRUCTTREEFROMGIVENINORDERAND
PREORDERTRAVERSALS
Let us consider the below traversals:
Inorder sequence: D B E A F C
Preorder sequence: A B D E C F
Solution:InaPreordersequence,leftmostelementis
therootofthetree.Soweknow‘A’isrootforgiven
sequences.Bysearching‘A’inInordersequence,
wecanfindoutallelementsonleftsideof‘A’arein
leftsubtreeandelementsonrightareinright
subtree.Soweknowbelowstructurenow.
45
SOLUTION
Thenodeappearinthefirstpositionpreorderis
alwaystheroot.Sohere,‘A’istheroot.
A
Now,takeone-onenodefrompreorderandobserve
itspositioninpostorder.LikehereBisnextin
preorder.BisbeforeAinpostorder,soitchildofA.
A
B
50
Next node in preorder is D. D is before B in postorder.
Next node in preorder is G. G is before D in postorder.
51
Next node in preorder is H. H is before D in postorder.
But D is already having a left child. H will become right
child of D.
H
•Next node in preorder is K. K is before H in postorder.
52
Threaded Binary Trees
•Too many null pointers in current representation of binary trees
n: number of nodes
number of non-null links: n-1
total links: 2n
null links: 2n-(n-1)=n+1
•Thisspacemaybemoreefficientlyusedbyreplacingthenull
entriesbysomeothertypeofinformation.
•Wewillreplacenullentriesbyspecialpointerswhichpointto
nodeshigherinthetree.
•Thesespecialpointersarecalled“threads”,andbinarytrees
withsuchpointersarecalledthreadedtree.
•Thethreadsinabinarytreeareusuallyindicatedbydottedlines.
56
THREADEDBINARYTREES
Tree can be threaded using
•One way threading:
i.Right-in–threaded:athreadwillappearinthe
RIGHTNullfieldofeachnodeandwillpointto
thesuccessorofthatnodeunderinordertraversal.
ii.Left-in-threaded:athreadwillappearintheLEFT
Nullfieldofeachnodeandwillpointtothe
predecessorofthatnodeunderinordertraversal.
•Twowaythreading(fullythreadedtree):bothleftand
rightNullpointerscanbeusedtopointtopredecessor
andsuccessorofthatnodeunderinordertraversal.
57
118
Advantages
1.Search is O(log N) since AVL trees are always balanced.
2.Insertion and deletions are also O(logn)
3.The height balancing adds no more than a constant factor to the speed of
insertion.
Disadvantages
1.Difficult to program & debug; more space for balance factor.
2.Asymptotically faster but rebalancing costs time.
3.Most large searches are done in database systems on disk and use other
structures (e.g. B-trees).
Pros and Cons of AVL Trees
M-way search tree
Searching , Insertion and Deletion
119
DEFINITION
Amulti-waytreeoforderm(oranm-waytree)isatreeTin
which
i.Eachnodesholdbetween1tom-1distinctkeysandeach
nodehas,atmostmchildnodes.
ii.Inanode,valuesarestoredinascendingorder:K
1<K
2<
...<K
m-1
iii.Thesubtreesareplacedbetweenadjacentvalues:each
valuehasaleftandrightsubtree.
k
irightsubtree=k
i+1leftsubtree.
Allthevaluesink
ileftsubtreeare<k
i
Allthevaluesink
irightsubtreeare>k
i
iv.EachofthesubtreeA
i,1≤i≤marealsom-waysearchtrees.
120
CASE2
To delete 12 (in the figure of slide 120), we find the
node [7,12] accommodates 12 and key satisfies (A
i≠
NULL, A
j = NULL). Hence we choose the largest of the
keys from the node pointed to by A
i10 and replace 12 with
10.
128
SEARCHINGINAB-TREE
Searching for a key in a B-tree is similar to one an
m-way search tree. The number of accesses
depends on the height h of the B-tree.
135
INSERTIONINTOAB-TREE
137
Consider the B-tree of order 5 shown below. Insert the elements 4,5, 58, 6 in
The order given.
AFTERINSERTION
138
139
Suppose we start with an empty B-tree and keys arrive in the
following order:1 12 8 2 25 6 14 28 17 7 52 16 48 68
3 26 29 53 55 45
We want to construct a B-tree of order 5
The first four items go into the root:
To put the fifth item in the root would violate condition
Therefore, when 25 arrives, pick the middle key to make a new
root
CONSTRUCTINGAB-TREE
12812
140
CONSTRUCTINGAB-TREE(CONTD.)
12
8
1225
6, 14, 28 get added to the leaf nodes:
12
8
12146 2528
141
CONSTRUCTINGAB-TREE(CONTD.)
Adding 17 to the right leaf node would over-fill it, so we take the
middle key, promote it (to the root) and split the leaf
817
1214 2528126
7, 52, 16, 48 get added to the leaf nodes
817
1214 2528126 16 48527
142
CONSTRUCTINGAB-TREE(CONTD.)
Adding 68 causes us to split the right most leaf, promoting 48 to the
root, and adding 3 causes us to split the left most leaf, promoting 3
to the root; 26, 29, 53, 55 then go into the leaves
381748
525355682526282912 67 121416
Adding 45 causes a split of25262829
and promoting 28 to the root then causes the root to split
144
Suppose we start with an empty B-tree and keys arrive in the
following order: 10 20 50 60 40 80 100 70 130 90 30 120 140
25 35 160 180
We want to construct a B-tree of order 5
CONSTRUCTINGAB-TREE
70
25 40 100140
2010 3035 5060 8090120130 160180
146
CASE#1: SIMPLELEAFDELETION
122952
2791522 5669723143
Delete 2: Since there are enough
keys in the node, just delete it
Assuming a 5-way
B-Tree, as before...
147
CASE#2: SIMPLENON-LEAFDELETION
122952
791522 5669723143
Delete 52
Borrow the predecessor
or (in this case) successor
56
148
CASE#4: TOOFEWKEYSINNODEANDITS
SIBLINGS
122956
791522 69723143
Delete 72
Too few keys!
Join back together
EXAMPLE
154
OntheB-treeoforder3givenbelow,performthe
followingoperationsintheorderoftheir
appearance:
Insert75,57delete35,65
SOLUTION
155
ALGORITHMTOFINDTHENO. OFLEAFNODES
INTHEBINARYTREE
get_leaf_node(node)
1. If node==Null then
Return 0
2. If left[node]=Null && right[node]==Null then
Return 1
3. Else
Return get_leaf_node(left[node])+
get_leaf_node(right[node])
156
HEAPSORT
157
A DATASTRUCTUREHEAP
A heapis an array object that can be viewed as a
nearly complete binary tree.
35
2 4
1
6
6 5 3 24 1
1
2
3
4 5 6
158
159
ARRAYREPRESENTATION OFHEAPS
A heap can be stored as an array
A.
Root of tree is A[1]
Left child of A[i] = A[2i]
Right child of A[i] = A[2i + 1]
Parent of A[i] = A[ i/2]
160
HEAPTYPES
Max-heaps(largestelementatroot),havethemax-heap
property:
for all nodes i, excluding the root:
A[PARENT(i)] ≥ A[i]
Min-heaps(smallestelementatroot),havethemin-heap
property:
for all nodes i, excluding the root:
A[PARENT(i)] ≤ A[i]
161
ADDING/DELETINGNODES
New nodes are always inserted at the bottom level (left to right)
Nodes are removed from the bottom level (right to left)
162
OPERATIONSONHEAPS
Maintain/Restore the max-heap property
MAX-HEAPIFY
Create a max-heap from an unordered array
BUILD-MAX-HEAP
Sort an array in place
HEAPSORT
164
EXAMPLE
MAX-HEAPIFY(A, 2, 10)
A[2] violates the heap property
A[2] A[4]
A[4] violates the heap property
A[4] A[9]
Heap property restored
165
MAINTAININGTHEHEAPPROPERTY
Assumptions:
Left and Right
subtrees of i are
max-heaps
A[i] may be
smaller than its
children
Alg:MAX-HEAPIFY(A, i, n)
1.l ← LEFT(i)
2.r ← RIGHT(i)
3.ifl ≤ n and A[l] > A[i]
4.thenlargest ←l
5.elselargest ←i
6.ifr ≤ n and A[r] > A[largest]
7.thenlargest ←r
8.iflargest i
9.thenexchange A[i] ↔ A[largest]
10. MAX-HEAPIFY(A, largest, n)
166
BUILDINGAHEAP
Alg:BUILD-MAX-HEAP(A)
1.n= length[A]
2.fori ←n/2downto1
3. doMAX-HEAPIFY(A, i, n)
Convert an array A[1 … n] into a max-heap (n = length[A])
The elements in the subarray A[(n/2+1) .. n] are leaves
Apply MAX-HEAPIFY on elements between 1 and n/2
2
14 8
1
16
7
4
3
9 10
1
2 3
4 5 6 7
8 9 10
4132169101487A:
168
HEAPSORT
Goal:
Sort an array using heap representations
Idea:
Build a max-heapfrom the array
Swap the root (the maximum element) with the last element
in the array
“Discard” this last node by decreasing the heap size
Call MAX-HEAPIFY on the new root
Repeat this process until only one node remains