elementary data structures - tohoku university official ... data structures 9 the queue adt ( 2.1.2)...

31
Elementary Data Structures Stacks, Queues, & Lists Trees

Upload: truongxuyen

Post on 27-Mar-2018

223 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures

Stacks, Queues, & ListsTrees

Page 2: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 2

The Stack ADT (§2.1.1)The Stack ADT stores arbitrary objectsInsertions and deletions follow the last-in first-out schemeThink of a spring-loaded plate dispenserMain stack operations:

push(object): inserts an elementobject pop(): removes and returns the last inserted element

Auxiliary stack operations:

object top(): returns the last inserted element without removing itinteger size(): returns the number of elements storedboolean isEmpty(): indicates whether no elements are stored

Page 3: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 3

Applications of Stacks

Direct applicationsPage-visited history in a Web browserUndo sequence in a text editor

Indirect applicationsAuxiliary data structure for algorithmsComponent of other data structures

Page 4: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 4

Array-based Stack (§2.1.1)Algorithm pop():

if isEmpty() thenthrow EmptyStackException

else t ← t − 1return S[t + 1]

A simple way of implementing the Stack ADT uses an arrayWe add elements from left to rightA variable t keeps track of the index of the top element (size is t+1)

S0 1 2 t

Algorithm push(o)if t = S.length − 1 then

throw FullStackExceptionelse t ← t + 1S[t] ← o

Page 5: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 5

Growable Array-based Stack (§1.5)

In a push operation, when the array is full, instead of throwing an exception, we can replace the array with a larger oneHow large should the new array be?

incremental strategy: increase the size by a constant cdoubling strategy: double the size

Algorithm push(o)if t = S.length − 1 then

A ← new array ofsize …

for i ← 0 to t doA[i] ← S[i]S ← A

t ← t + 1S[t] ← o

Page 6: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 6

Comparison of the Strategies

We compare the incremental strategy and the doubling strategy by analyzing the total time T(n) needed to perform a series of n push operationsWe assume that we start with an empty stack represented by an array of size 1

Page 7: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 7

Analysis of the Incremental Strategy

We replace the array k = n/c timesThe total time T(n) of a series of n push operations is proportional to

n + c + 2c + 3c + 4c + … + kc =n + c(1 + 2 + 3 + … + k) =

n + ck(k + 1)/2Since c is a constant, T(n) is O(n + k2),i.e., O(n2)

Page 8: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 8

Direct Analysis of the Doubling Strategy

We replace the array k = log2 n timesThe total time T(n) of a series of n push operations is proportional ton + 1 + 2 + 4 + 8 + …+ 2k =

n + 2k + 1 −1 = 2n −1T(n) is O(n)

geometric series

1

2

14

8

Page 9: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 9

The Queue ADT (§2.1.2)The Queue ADT stores arbitrary objectsInsertions and deletions follow the first-in first-out schemeInsertions are at the rear of the queue and removals are at the front of the queueMain queue operations:

enqueue(object): inserts an element at the end of the queueobject dequeue(): removes and returns the element at the front of the queue

Auxiliary queue operations:object front(): returns the element at the front without removing itinteger size(): returns the number of elements storedboolean isEmpty(): indicates whether no elements are stored

ExceptionsAttempting the execution of dequeue or front on an empty queue throws an EmptyQueueException

Page 10: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 10

Applications of Queues

Direct applicationsWaiting linesAccess to shared resources (e.g., printer)

Indirect applicationsAuxiliary data structure for algorithmsComponent of other data structures

Page 11: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 11

Singly Linked ListA singly linked list is a concrete data structure consisting of a sequence of nodesEach node stores

elementlink to the next node

next

elem node

A

B C D

Page 12: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 12

Queue with a Singly Linked ListWe can implement a queue with a singly linked list

The front element is stored at the first nodeThe rear element is stored at the last node

The space used is O(n) and each operation of the Queue ADT takes O(1) time

f

r

nodes

elements

Page 13: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 13

List ADT (§2.2.2)

The List ADT models a sequence of positionsstoring arbitrary objectsIt allows for insertion and removal in the “middle”Query methods:

isFirst(p), isLast(p)

Accessor methods:first(), last()before(p), after(p)

Update methods:replaceElement(p, o), swapElements(p, q) insertBefore(p, o), insertAfter(p, o),insertFirst(o), insertLast(o)remove(p)

Page 14: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 14

Doubly Linked Listprev next

elem node

A doubly linked list provides a natural implementation of the List ADTNodes implement Position and store:

elementlink to the previous nodelink to the next node

Special trailer and header nodes

nodes/positions

elements

trailerheader

Page 15: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 15

InsertionWe visualize operation insertAfter(p, X), which returns position q

p

A B C

p

X

qA B C

p q

A B X C

Page 16: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 16

DeletionWe visualize remove(p), where p = last()

A B C D

p

D

pA B C

A B C

Page 17: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 17

Trees (§2.3)In computer science, a tree is an abstract model of a hierarchical structureA tree consists of nodes with a parent-child relationApplications:

Organization chartsFile systems

Computers”R”Us

Sales R&DManufacturing

Laptops DesktopsUS International

Europe Asia Canada

Page 18: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 18

Tree Terminology

subtree

Root: node without parent (A)Internal node: node with at least one child (A, B, C, F)External node (a.k.a. leaf ): node without children (E, I, J, K, G, H, D)Ancestors of a node: parent, grandparent, grand-grandparent, etc.Depth of a node: number of ancestorsHeight of a tree: maximum depth of any node (3)Descendant of a node: child, grandchild, grand-grandchild, etc.

A

B DC

G HE F

I J K

Subtree: tree consisting of a node and its descendants

Page 19: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 19

Tree ADT (§2.3.1)We use positions to abstract nodesGeneric methods:

integer size()boolean isEmpty()objectIterator elements()positionIterator positions()

Accessor methods:position root()position parent(p)positionIterator children(p)

Query methods:boolean isInternal(p)boolean isExternal(p)boolean isRoot(p)

Update methods:swapElements(p, q)object replaceElement(p, o)

Page 20: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 20

Preorder Traversal (§2.3.2)A traversal visits the nodes of a tree in a systematic mannerIn a preorder traversal, a node is visited before its descendants Application: print a structured document

Algorithm preOrder(v)visit(v)for each child w of v

preorder (w)

1Make Money Fast!

1. Motivations References2. Methods

2.1 StockFraud

2.2 PonziScheme1.1 Greed 1.2 Avidity

2 5 9

6 7 83 42.3 BankRobbery

Page 21: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 21

Postorder Traversal (§2.3.2)In a postorder traversal, a node is visited after its descendantsApplication: compute space used by files in a directory and its subdirectories

Algorithm postOrder(v)for each child w of v

postOrder (w)visit(v)

9cs16/

todo.txt1Khomeworks/ programs/

DDR.java10K

Stocks.java25K

h1c.doc3K

h1nc.doc2K

3 78

64 51 2Robot.java

20K

Page 22: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 22

Binary Trees (§2.3.3)A binary tree is a tree with the following properties:

Each internal node has two childrenThe children of a node are an ordered pair

We call the children of an internal node left child and right childAlternative recursive definition: a binary tree is either

a tree consisting of a single node, ora tree whose root has an ordered pair of children, each of which is a binary tree

Applications:arithmetic expressionsdecision processessearching

A

B C

D E F G

H I

Page 23: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 23

Arithmetic Expression TreeBinary tree associated with an arithmetic expression

internal nodes: operatorsexternal nodes: operands

Example: arithmetic expression tree for the expression (2 × (a − 1) + (3 × b))

+

××

−2

a 1

3 b

Page 24: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 24

Decision TreeBinary tree associated with a decision process

internal nodes: questions with yes/no answerexternal nodes: decisions

Example: dining decision

Want a fast meal?

How about coffee? On expense account?

Starbucks McDonald’s Chez Nous

NoYes

Yes No Yes No

Skylark

Page 25: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 25

Properties of Binary TreesNotationn number of nodese number of

external nodesi number of internal

nodesh height

Properties:e = i + 1n = 2e − 1h ≤ ih ≤ (n − 1)/2e ≤ 2h

h ≥ log2 eh ≥ log2 (n + 1) − 1

Page 26: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 26

Inorder TraversalIn an inorder traversal a node is visited after its left subtree and before its right subtreeApplication: draw a binary tree

x(v) = inorder rank of vy(v) = depth of v

Algorithm inOrder(v)if isInternal (v)

inOrder (leftChild (v))visit(v)if isInternal (v)

inOrder (rightChild (v))

3

1

2

5

6

7 9

8

4

Page 27: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 27

Euler Tour TraversalGeneric traversal of a binary treeIncludes a special cases the preorder, postorder and inorder traversalsWalk around the tree and visit each node three times:

on the left (preorder)from below (inorder)on the right (postorder)

+

×

−2

5 1

3 2

LB

Page 28: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 28

Printing Arithmetic ExpressionsAlgorithm printExpression(v)

if isInternal (v)print(“(’’)inOrder (leftChild (v))

print(v.element ())if isInternal (v)

inOrder (rightChild (v))print (“)’’)

Specialization of an inordertraversal

print operand or operator when visiting nodeprint “(“ before traversing left subtreeprint “)“ after traversing right subtree

+

××

−2

a 1

3 b((2 × (a − 1)) + (3 × b))

Page 29: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 29

Linked Data Structure for Representing Trees (§2.3.4)

A node is represented by an object storing

ElementParent nodeSequence of children nodes

Node objects implement the Position ADT

∅ ∅

A D F

∅C

∅E

B

B

DA

C

F

E

Page 30: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 30

Linked Data Structure for Binary Trees

A node is represented by an object storing

ElementParent nodeLeft child nodeRight child node

Node objects implement the Position ADT

∅ ∅

∅ ∅ ∅ ∅

B

A D

C E

B

A D

C E

Page 31: Elementary Data Structures - Tohoku University Official ... Data Structures 9 The Queue ADT ( 2.1.2) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in

Elementary Data Structures 31

Array-Based Representation of Binary Trees

nodes are stored in an array

let rank(node) be defined as follows:rank(root) = 1if node is the left child of parent(node),

rank(node) = 2*rank(parent(node))if node is the right child of parent(node),

rank(node) = 2*rank(parent(node))+1

1

2 3

64 5

10 11

A

HG

FE

D

C

B

J

7