0% found this document useful (0 votes)
46 views67 pages

DSA Chapter 6 - Tree

Uploaded by

beshahashenafi32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views67 pages

DSA Chapter 6 - Tree

Uploaded by

beshahashenafi32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

CHAPTER 6

D A T A STRUCTURES A N D ALGORITHMS

Tree
Data
DATA STRUCTURE A N D ALGORITHM
Structure 1
CONTENTS

◾ Tree Data
Structure:
◾ D efinition of tree,

◾ Basic
terminologies,

◾ Types of trees:-
◾ n-ary tree,
Binary tree, BST,
A V L tree, full
BT, complete B T
,Balanced B T .

◾ Basic operations on
tree,
DATA STRUCTURE A N D ALGORITHM 2
◾ Tree traversal
m e thods:
6.1. T R E E D A T A S T R U C T U R E

◾ So far w e have seen


◾ arrays, linked list, stacks, queues
◾ Disadvantages ?
◾ They are linear structures (Time is Money)
◾ Tree
◾ Non-linear structures (every data element m a y have more than one predecessor as well as
successor)
◾ Probably the most fundamental structure in computing
◾ Hierarchical structure
◾ Tree consist of nodes and edges (arcs)
◾ Applications:
◾ Organization charts
◾ File systems
◾ Programming environments

DATA STRUCTURE A N D ALGORITHM 3


REAL W ORLD TREE vs TREE DATA STRUCTURE

DATA STRUCTURE A N D ALGORITHM 4


CONT..

◾ A tree is a collection of elements called nodes connected by directed (or undirected) edges
(that contains no cycles). Each node contains some value.

◾ A tree can be empty with no nodes or a tree is a structure consisting of one node
called the root and zero or one or more subtrees.

◾ A tree has following general properties:

◾ O n e node is distinguished as a root;

◾ Every node (exclude a root) is connected by a directed edge from exactly one other node; A
direction
is: parent -> children
DATA STRUCTURE A N D ALGORITHM 5
DATA STRUCTURE A N D ALGORITHM 6
6.2. BASIC TERMINOLOGIES IN TREE

◾ Root: - The node at the top of the tree is called root. There is only one root per tree and
one path from the root node to any node.(Root – node with no parent)
◾ Child: - The node below a given node connected by its edge downward is called its child
node (left child or right child).
◾ Edge: - The connection between one node and another.
◾ Parent: - Any node except the root node has one edge upward to a node called parent.
◾ Leaves:- Nodes with no children are called leaves, or external nodes.
◾ Internal nodes:- Nodes which are not leaves, are called internal nodes. Internal nodes have
at least one child.

DATA STRUCTURE A N D ALGORITHM 7


2, 3 and 4 are a child of
1
2, 5,6,7,9 and 10 are 1 is a parent of 2,3 and
leaves 4

1,3,4 and 8 are


internal nodes

5, 6 and 7 are a child of


3

3 is a parent of 5,6 and 9 and 10 are a child of


7 8
DATA STRUCTURE A N D ALGORITHM 8 is a parent of 9 and 8

10
CONT..

◾ Siblings:- Nodes with the same parent are called siblings.

◾ Depth of a node:- The depth of a node is the number of edges from the root to the node.

◾ The height of a node:- is the number of edges from the node to the deepest leaf.

◾ The height of a tree:- is a height of a root. Or (the m a x i m u m depth of any node within the tree)

◾ Descendant: - A node reachable by repeated proceeding from parent to child.(child, grandchild,


grand-
grandchild, etc)

◾ Ancestor: -A node reachable by repeated proceeding from child to parent.(parent, grandparent,


grand-
grandparent, etc.)
DATA STRUCTURE A N D ALGORITHM 9
2, 3 and 4 are
Height of 8 = 1 siblings
Height of 2 = 0
Height of 4 = 2
Height of the Tree = D epth of 8 = 2
3 Depth of 2 = 1
D epth of 9 = 3

5, 6 and 7 are
siblings

D escendant of 4 = 8,9 and 10


Ancestor of 7 = 3 and 1 9 and 10 are
siblings
DATA STRUCTURE A N D ALGORITHM 10
CONT..

◾ Degree of a node: is the total nu m ber of its children

◾ Degree of a tree: the m a x i m u m degree of a node in the tree.

◾ Path: -A sequence of nodes and edges connecting a node with a descendant.

◾ Length of this path: is the number of edges connecting the nodes in the path.

◾ Level: -Level of a node represents the generation of a node. If the root node is at level 0, then its
next
child node is at level 1, its grandchild is at level 2, and so on.
◾ Subtree − Subtree represents the descendants of a node.

◾ Traversing − Traversing means passing through nodes in a specific order.


DATA STRUCTURE A N D ALGORITHM 11
Node 1 has 3 subtrees

Degree of 8 = 2
D egree of 3 = 3
D egree of 4 = 1
D egree of the Tree =
3

DATA STRUCTURE A N D ALGORITHM 12


TYPES OF TREE

Types of Tree
◾ General tree, Binary Tree, Binary search tree, n-ary tree, A V L tree or height balanced binary
tree,
Red-Black tree…..etc.
General Tree or Tree
◾ Every node can have any number of sub-trees, there is no maximum. Different number is
possible of each node.
Binary Tree
◾ The m ost basic for m of tree structure.
◾ A binary tree is a tree where each node is restricted to having at most two children, and each
child is designated as either a left child or right child.
DATA STRUCTURE A N D ALGORITHM 13
Which one of the following is Binary Tree?

A, B, C, D, E,

DATA STRUCTURE A N D ALGORITHM 14


BINARY TREE
Calculating m i n i m u m and m a x i m u m heights from the number of nodes
If there are n nodes in binary tree,
◾ M axi m u m height of the binary tree is n-1 and

◾ M ini m u m height is floor(𝐥𝐨𝐠 𝟐 𝒏)

◾ Example; find the m a x i m u m and m i n i m u m height for a binary tree with 5


nodes?
◾ M a x i m u m height 5-1 = 4

◾ Minimu m height is floor(𝐥𝐨𝐠 𝟐 𝟓) = 2

DATA STRUCTURE A N D ALGORITHM 15


CONT..
Calculating m i n i m u m and m a x i m u m number of nodes from height
If the binary tree has height h,
◾ M ini m u m nu m b er of nodes is h+1

◾ M axi m u m nu m b er of nodes is 𝟐(𝒉+𝟏) − 𝟏

◾ Example; find the m a x i m u m and m i n i m u m possible number of nodes for a binary tree with Height = 2
?
◾ M a x i m u m height 2+1 = 3

◾ M i n i m u m height 𝟐(𝒉+𝟏) − 𝟏 = 7

DATA STRUCTURE A N D ALGORITHM 16


CONT..

◾ In a binary tree, a m a x i m u m possible number of nodes in each level is equals


to

𝟐𝑳 (considering the root at level
0)
◾ 𝟐𝑳−𝟏 (considering the root at w h e re L is level of the binary
level 1) tree.

DATA STRUCTURE A N D ALGORITHM 17


FULL BINARY TREE

◾ A binary tree is a full binary tree if it contains the maximum possible number of nodes in
all levels.
◾ In a full binary tree, each node has two children or no child at all (for leaves node ).
◾ The total number of nodes in a full binary tree of height h is 2h+1 - 1 (considering the root
at level 0).

Height Total N o of Nodes


0 1
1 3
2 7
3 15

DATA STRUCTURE A N D ALGORITHM 18


COMPLETE BINARY TREE

◾ A binary tree is said to be a complete binary tree if all its levels except the last level
have the m a x i m u m number of possible nodes, and all the nodes of the last level appear as
far left as possible.
◾ In a complete binary tree, all the leaf nodes are at the last and the second last level, and
the levels are filled from left to right.

DATA STRUCTURE A N D ALGORITHM 19


PERFECT BINARY TREE

◾ A perfect binary is a binary tree in which all internal have two children and all leaves
tree nodes
have the same depth or same level.

Perfect binary trees of height h = 0, 1, 2, 3, and


4.
◾ A perfect binary tree of height h has 2 h + 1 – 1 nodes.
◾ There are 2 h Leaf Nodes
◾ Over half of all the nodes in a perfect binary tree are leaf
nodes.
DATA STRUCTURE A N D ALGORITHM 20
BALANCED BINARY TREE

◾ A balanced binary tree is a binary tree in which for each node


◾ The left and the right sub-tree heights differ by at most one and
◾ The left sub-tree is balanced and
◾ The right sub-tree is balanced.

Which one of the following is balanced binary tree


?

DATA STRUCTURE A N D ALGORITHM 21


BINARY SEARCH TREE (BST )

◾ BST is a tree in which all the nodes follow the below-mentioned properties

◾ The left sub-tree of a node has a key less than or equal to its parent node's key.
◾ The right sub-tree of a node has a key greater than or equal to its parent node's
key.

DATA STRUCTURES & ALGORITHM (ECEG4171) DAWIT K. 12/19/2016 22


N -ARY TREES
◾ A binary tree restricts the number of children of each node to two. A more general N-ary
tree restricts the number of children to N .
◾ A n N-ary tree is a tree where each node has at most N children.
◾ For example, a 3-ary tree or ternary tree restricts each node to having at most three
children. A
quaternary tree limits its children to four.

DATA STRUCTURE A N D ALGORITHM 23


TREE TRAVERSAL

◾ Traversal is a process to visit all the nodes of a tree and m a y print their values too.

◾ There are three ways which w e use to traverse a tree −

◾ In-order Traversal

◾ Pre-order Traversal

◾ Post-order Traversal

◾ Generally, w e traverse a tree to search or locate a given item or key in the tree or to print
all
the values it contains.
D ATA STRUCTURES & 12/19/2016 24
ALGO RITHM
IN-ORD ER TRAVERSAL

◾ In this traversal method, the left subtree is visited first, then the root and later the right sub-
tree.
◾ If a binary search tree is traversed in-order, the output will produce sorted key values in an
ascending order.

D →B→E→A→F→C →
G

D ATA STRUCTURES & 12/19/2016 25


ALGO RITHM
PRE-ORD ER TRAVERSAL
◾ In this traversal method, the root node is visited first, then the left subtree and finally the
right subtree.

A→B→D →E→C →F→


G

D ATA STRUCTURES & 12/19/2016 26


ALGO RITHM
POST-ORDER TRAVERSAL

◾ In this traversal method, the root node is visited last, hence the name. First w e traverse the
left subtree, then the right subtree and finally the root node.

D →E→B→F→G→C →
A

D ATA STRUCTURES & 12/19/2016 27


ALGO RITHM
PART 2:
TREE DS

• BST Operations
• BST Implementation
• Using array
• Using linked list
• A V L Tree
• Heap Data Structure
• Heap Operations
• Expression tree
DATA STRUCTURE A N D ALGORITHM 28
OPERATIONS O N BINARY SEARCH TREE

The following are the operations commonly performed on a BST:

1. Inserting a key: - Insert a n e w node with a given key in its correct place in
BST

2. Searching a key: - Search a node in the BST w ith the given key

3. Deleting a key: - Remove a node with a given key from BST

4. Traversing the tree: - In-order, pre-order and post-order

5. Finding maximum values: - G o to the right most leaf starting from root

6. Finding minimum values: - G o to the left most leaf starting from the root
DATA STRUCTURE A N D ALGORITHM 29
BST- INSERTION OPERATION

◾ If the tree is empty, the very first insertion creates the tree. Then the first key becomes the
root.

◾ Afterwards, whenever an element is to be inserted,

◾ First locate its proper location. Start searching from the root node, then

◾ If the n e w key is less than the root’s key, search for the empty location in the left subtree
and
insert the ne w key.

◾ Otherwise, search for the empty location in the right subtree and insert the data.

◾ Remember no matter the value of the n e w key to be inserted, it will be inserted as leaf node of
the
DATA STRUCTURE A N D ALGORITHM 30
tree. (unless the n e w key is already in the BST).
Example: Insert the following key’s in BST. 23, 5, 34, 56, 9, 41, -1, 8, 73

23 23 23
23 23
23
5 5 34 5 34 5 34 5 34

56 9 56 9 56

23 23 23 41

5 34 5 34 5 34

- 9 56 - 9 56 - 9 56
1 1 1
DATA STRUCTURE A N D ALGORITHM
41 8 41 8 41 73 31
BST- SEARCHING OPERATION

To search for a target key,


◾ W e first compare it with the key at the root of the tree.
◾ If it is the same, then the root will be returned.
◾ If it is less than the key at the root, search for the target key in the left
subtree,
◾ else search in the right 41  23 & 41>23
subtree. 23 go right
◾ Example: Search for
41?
34 41  34 & 41>34
5
go right

56 41  56 & 41<56
- 9 go left
1
DATA STRUCTURE A N D ALGORITHM 32

8 4 73
1
BST- DELETION O PERATION
◾ Complexity of deletion depends on the node
◾ There are three cases to consider:
◾ Case 1: The node to be deleted is a leaf (has no children).
◾ Case 2: The node to be deleted has one child.
◾ Case 3: The node to be deleted has two children.

◾ Case 1: The node to be deleted is a leaf (has no


children).
◾ Simply remove the leaf node from the tree by removing
the link with its parent. 23
23
◾ Example: Delete 8 from
34 5 34
BST. 5

56 -1 9 56
-1 9
DATA STRUCTURE A N D ALGORITHM 33

X 8 41 73 41 73
CONT..

Case 2: The node to be deleted has one child.


◾ Just make the child of the deleting node, the child of the
grandparent.
◾ Example Delete 9 from BST
23 23 23

5 34 5 34 5 34

-1 9 56 -1 56 -1 8 56

8 41 73 8 41 73 41 73

DATA STRUCTURE A N D ALGORITHM 34


CONT..

Case 3: The node to be deleted has two child.

◾ The question is which subtrees should the parent of the deleted node be linked to, what
should
be done with the other subtrees, and where should the remaining subtrees be linked.

◾ Method 1:

◾ G o to the right subtree of the deleting node,

◾ Select the smallest node called in-order successor and Replace with the deleting node.

◾ If the node (in-order successor node) to replace the deleting node has right child, make this node a
left
child of its grand parent
DATA STRUCTURE A N D ALGORITHM 35
23 Delete 34 23

5 34
5 41
Right sub-
tree
- 9 30 56
- 9 30 56
1
1

8 73
32 41 8 32 73

in-order
23 successor 30
Delete 23

5 34 5 34

in-order
- 9 30 successo 56 - 9 32 56
1 1
DATA STRUCTURE A N D ALGORITHM r 36

8 32 41 73 8 41 73
CONT..

◾ Method 2:

◾ G o to the left subtree of the deleting node,

◾ Select the greatest node called in-order predecessor and Replace with the deleting node.

◾ If the node (in-order predecessor node) to replace the deleting node has left child, make this node a

right child of its grand parent

DATA STRUCTURE A N D ALGORITHM 37


23 Delete 34 23

5 Left sub- 34 5 32
tree
- 9 30 56 - 9 30 56
1 1

8 8 73
32 41 41
73

23
in-order predecessor 9
Delete 23

5 34 5 34

-1 9 30 56 - 8 30 56
1
DATA STRUCTURE A N D ALGORITHM 38

8 in-order 32 41 73 32 41 73
predecesso
BST- OTHER OPERATIONS

◾ Traversing the tree:


-
◾ In-order = -1, 5, 8, 9, 23, 34, 41, 56,
23
73
◾ pre-order = 23, 5, -1, 9, 8, 34, 56, 41,
73
◾ post-order = -1, 8, 9, 5, 41, 73, 56, 34, 5 34
23
◾ Finding maximum values:
- - 9 56
◾ G o to the right most leaf starting fro m root
= 73 1
◾ Finding minimum values:
- 8 41 73
◾ G o to the left most leaf starting from the root =
-1

DATA STRUCTURE A N D ALGORITHM 39


BST IMPLEMENTATION USING ARRAY
◾ One of the ways to represent a tree using an array is to store the nodes level-by-level,
starting fro m the level 0 w here the root is present.
◾ A complete binary tree of height h has (2h+1 - 1) nodes in it. The nodes can be stored in a
one-
dimensional array of size 2h+1 - 1 is needed for the same.

DATA STRUCTURE A N D ALGORITHM 40


This representation of binary trees using an array seems to be the
easiest. Certainly, it can be used for all binary trees.
CONT..
For any node with index i, 0 ≤ i ≤ n - 1, w e can find the location of its parent, left child
and right child using the following formula.
◾ 1. Parent_index = floor( (i - 1)/2 ) if i  0; if i = 0, then it is the root (has no
parent).
◾ 2. Lchild_index = 2i + 1 if 2i + 1 ≤ n - 1; if 2i ≥ n, then i has no left child.
◾ 3. Rchild_index = 2i + 2 if 2i + 2 ≤ n - 1; if (2i + 1) ≥ n, then i has no right child.

DATA STRUCTURE A N D ALGORITHM 41


ADVA N TAGES A N D DISADVA N TAGES

Advantages:
1. Any node can be accessed from any other node by calculating the index.
2. The data is stored without any pointers to its successor or predecessor.
3. In the programming languages, where dynamic m e m o r y allocation is not possible (such as
BASIC, fortran ), array representation is the only means to store a tree.
Disadvantages:
4. Other than full binary trees, majority of the array entries m a y be empty.
5. It allows only static representation.
6. Insertion and deletion operation requires lots of data movement.

DATA STRUCTURE A N D ALGORITHM 42


These problems can be overcome by the use of
linked representation.
BST-LINKED LIST IMPLEMENTATION
◾ Using linked list, each node will have three fields — Lchild, Data, and
Rchild.
◾ If needed, the fourth parent field can be included.
◾ The root of the tree is stored in the data m e m b e r root of the tree.
◾ This data m e m b e r provides an access pointer to the tree.

DATA STRUCTURE A N D ALGORITHM 43

Here, 0 (zero) stored at Lchild or Rchild fields represents that the respective child is
not present. Alternately NULL can be used instead of zero.
DATA STRUCTURE A N D ALGORITHM 44
ADVA N TAGES A N D DISADVA N TAGES

Advantages:
1. The drawbacks of the sequential representation are overcome in this representation. In addition, for
unbalanced trees, the m e m o r y is not wasted.
2. Insertion and deletion operations are more efficient in this representation.
3. It is useful for dynamic data.
Disadvantages:
4. In this representation, there is no direct access to any node.
5. As compared to sequential representation, the memory needed per node is more. This is due to two link fields
(left child and right child for binary trees) in the node.
6. The programming languages not supporting dynamic memory management would not be useful for this
representation.
DATA STRUCTURE A N D ALGORITHM 45
AVL TREES

◾ A V L tree is a self-balancing binary search tree.


◾ N a m ed after A delson-V elskii and Landis
◾ Balance is defined by comparing the height of the two sub-trees
◾ In A V L tree, the heights of the two child subtrees of any node differ by at most one.
◾ If at any time they differ by more than one, rebalancing is done to restore this
property.
◾ Insertion and deletion m a y require the tree to be rebalanced by one or more tree
rotation.
◾ Recall:
◾ A n empty tree has height –1
◾ A tree with a single node has height 0
DATA STRUCTURE A N D ALGORITHM 46

AVL trees with 1, 2, 3, and 4 nodes:


AVL tree or not?

DATA STRUCTURE A N D ALGORITHM 47


WHY AVL TREE?

◾ Most BST operations takes O(h) time where h is the height of BST.

◾ The cost of this operations m a y become O(n) for a skewed binary tree.

◾ If w e make sure that height of the tree remains O(Log n) after every insertion and deletion,

then w e can guarantee an upper bound of O(Log n) for all these operations.

◾ The height of A V L tree is always O(Log n) where n is the number of nodes in the tree.

DATA STRUCTURE A N D ALGORITHM 48


◾ To keep the tree height-balanced, w e have to find out the balance factor of each node in the tree

after every insertion or deletion.

◾ The balance factor of a node T, BF(T), in a binary tree is hL - hR, where hL and h R are the

heights of the left and right subtrees of T, respectively.

◾ For any node T in an A V L tree, the BF(T) is equal to -1, 0, or 1.

◾ If a node is inserted or deleted from a balanced tree, then it m a y become unbalanced.

◾ So to rebalance it, the position of some nodes can be changed in proper sequence.

◾ This can be achieved by performing rotations of nodes.

DATA STRUCTURE A N D ALGORITHM 49


BALANCING AVL TREE

◾ Depends on the scenario whether a rotation should be performed towards left or


right.

◾ To balance itself, an A V L tree m a y perform the following four kinds of rotations

1. Left rotation (for Right Right (RR) problem)


Single rotations
2. Right rotation (for Left Left (LL) proble m )

3. Left-Right (LR) rotation (for Left Right (LR) problem)


Double rotations
4. Right-Left (RL) rotation (for Right Left (RL) problem)
DATA STRUCTURE A N D ALGORITHM 50
To have an unbalanced tree, we at least need a
tree of height 2.
LEFT ROTATION
◾ If a tree becomes unbalanced, w he n a node is inserted into the right subtree of the right
subtree, then w e perform a single left rotation −

23 23 23
R
34
34 34 34
R
23 56
56 56
Balanced A V L
Unbalanced A V L
Node 23 has become Left Balanced A V L
unbalanced R o tation
as 56 is inserted in
DATA STRUCTURE A N D ALGORITHM the right subtree of 23's right 51
subtree.
RIGHT ROTATION
◾ If a tree becomes unbalanced, w he n a node is inserted into the left subtree of the left
subtree, then w e perform a single right rotation −

56 56 56
L
34
34 34 34
L
23 56
23 23
Balanced A V L
Unbalanced A V L
Node 23 has become Left Balanced A V L
unbalanced R o tation
as 56 is inserted in
DATA STRUCTURE A N D ALGORITHM the left subtree of 23's left 52
subtree.
LEFT-RIGHT ROTATION
◾ Double rotations are slightly complex version of already explained versions of rotations.
◾ A left-right rotation is a combination of left rotation followed by right rotation.
◾ If a node inserted into the right subtree of the left subtree and the A V L becomes unbalanced
we
perform left-right rotation.

R
We first perform the left rotation on W e shall n o w right-rotate the
Unbalanced A V L the left subtree of C .This makes A, tree, making B the n e w root
Node C has become unbalanced as the left subtree of B. node of this subtree. C n o w
node B is inserted in the right becomes the right subtree of its
subtree N ode C is still unbalanced, however o w n left subtree. 53

of N ode C 's left subtree. now, it is because of the left-subtree The tree is now
DATA STRUCTURE A N D ALGORITHM
of the left- subtree. balanced.
RIGHT-LEFT ROTATION
◾ A right-left rotation is a combination of right rotation followed by left rotation.
◾ If a node inserted into the left subtree of the right subtree and the A V L becomes unbalanced
we perform left-right rotation.

We first perform the right rotation along A left rotation is perform ed by


Unbalanced A V L C node, making C the right subtree of m aking B the new root node of
Node A has become unbalanced as its own left subtree B. N ow, B becomes the subtree. A becom es the left
node B is inserted in the left the right subtree of A. subtree of its right subtree B.
subtree 54

of N ode A's Right subtree. N ode A is still unbalanced because of The tree is now
DATA STRUCTURE A N D ALGORITHM
the right subtree of its right subtree balanced.
and requires a left rotation..
Create A V L Tree for the following unsorted list of
keys.
◾ 21, 26, 30, 9, 4, 14, 28, 18, 15, 10, 2, 3,
7
26 26
21 21 21
21 30 21 30
26
30 9
26
A. B. C. D.

26 26 26 26 21

21 30 9 30 9 30 21 30 26
9

9 4 21 4 21 9 4 30
14

4 14 4 14 55

E. F
Create A V L Tree for the following unsorted list of
keys.
◾ 21, 26, 30, 9, 4, 14, 28, 18, 15, 10, 2, 3,
7

21
9 26

4 14 30

Continue inserting … … … … … … . .

DATA STRUCTURE A N D ALGORITHM 56


HEAP DATA STRUCTURE
A heap is a binary tree having the following properties:
1. It is a complete binary tree, that is, each level of the tree is completely filled, except the
bottom level, where it is filled from left to right.
2. It satisfies the heap-order property , that is,
◾ The key value of each node is greater than or equal to the key value of its children, or
◾ The key value of each node is lesser than or equal to the key value of its children.

Which one of the following is Heap?

57

DATA STRUCTURE A N D ALGORITHM


MIN-HEAP
◾ In min-heap, the key value of each node is lesser than or equal to the key value of its
children.
◾ Parent key must <= children’s key

◾ In addition, every path from root to leaf should be sorted in ascending order.

DATA STRUCTURE A N D ALGORITHM 58


MAX-HEAP
◾ A max-heap is where the key value of a node is greater than or equal to the key value of
its children.
◾ Parent key must >= children’s key

◾ In addition, every path from root to leaf should be sorted in descending order.
◾ In general, whenever the term ‘heap’ is used by itself, it refers to a max-heap

DATA STRUCTURE A N D ALGORITHM 59


OPERATIONS O N HEAPS

The basic operations on heaps are listed as follows:

1. Create - creates an em pty heap to w hich the root points

2. Insert - inserts an elem ent into the heap

3. Delete - deletes m a x (or min) element from the heap

4. ReheapUp - rebuilds the heap w he n w e use the insert() function

5. ReheapDown - rebuilds the heap w he n w e use the delete()


function

DATA STRUCTURE A N D ALGORITHM 60


ReheapUp
◾ Inserting a n e w node in the heap is always done at the end of the heap (leaf of last level).
◾ Sometimes the newly inserted node (the last node in the heap) becomes out of order.
◾ The reheapUp operation repairs the structure so that it is a heap by lifting the last element up
in
the tree until that element reaches a proper position in the tree.
◾ ReheapUp repairs a broken heap by lifting the last element up by repeatedly exchanging child–
parent keys until it reaches the correct location in the heap.

reheapU P 61
O riginal After Inserting reheapUP
36 36 Exchanged with 36 Exchanged with
Heap
DATA STRUCTURE A N D ALGORITHM 23 32
ReheapDown
◾ Deleting a node in the heap is always done at the top of the heap (root). A nd then the last
node in the heap replace the root position.
◾ Sometimes the n e w root becomes out of order.
◾ The reheapDown operation repairs the structure so that it is a heap by lifting the root element
down in the tree until that element reaches a proper position in the tree.
◾ ReheapDown repairs a broken heap by lifting the last element d o w n by repeatedly
exchanging parent-child keys until it reaches the correct location in the heap.

reheapDown 62
O riginal After deleting reheapDown
53 43 Exchanged with 41 Exchanged with
Heap
DATA STRUCTURE A N D ALGORITHM 21 21
INSERT
◾ A node can be inserted in a heap which has already been built, if there is an empty
location in the array.
◾ To insert a node, w e need to search the first empty leaf in the array. W e find it
immediately
after the last node in the tree.
◾ To insert a node, w e m o v e the n e w data to the first empty leaf and perform reheapUp.

63
Heap after insertion of 87 Heap after reheapUp Operation

DATA STRUCTURE A N D ALGORITHM


DELETE
◾ While removing a node from a heap, the most c o m m o n and meaningful logic is to delete
the root.
◾ The heap is thus left without a root.

◾ To reconstruct the heap, w e m ov e the data in the last heap node to the root and perform
reheapDown.

Heap after reheapDown Heap after reheapDown


Operation Operation

DATA STRUCTURE A N D ALGORITHM 64


Create Heap for the following unsorted list of
keys.
◾ 8, 20, 9, 4, 15, 10, 7, 22, 3, 12

DATA STRUCTURE A N D ALGORITHM 65


EXPRESSION TREE
◾ A binary tree storing or representing an arithmetic expression is called as expression tree.
◾ The leaves of an expression tree are operands. Operands could be variables or constants.
◾ The branch nodes (internal nodes) represent the operators.
◾ A binary tree is the most suitable one for arithmetic expressions as it contains either binary
or unary operators.

DATA STRUCTURE A N D ALGORITHM 66


CONT..

◾ If w e traverse this tree in pre-order, w e visit the nodes in the order of: /+xAB-CD-CE, and
this is a prefix for m of the infix expression.
◾ O n the other hand, if w e traverse the tree in post-order, the nodes are visited in the
following
order: ABxCD-E-/, which is a postfix equivalent of the infix notation.

DATA STRUCTURE A N D ALGORITHM 67

You might also like