Stacks, Queues and Hierarchical Collections

Similar documents
Stacks, Queues and Hierarchical Collections. 2501ICT Logan

Tree Applications. Processing sentences (computer programs or natural languages) Searchable data structures

Postfix (and prefix) notation

12 Abstract Data Types

TREES. Trees - Introduction

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,

Section 5.5. Left subtree The left subtree of a vertex V on a binary tree is the graph formed by the left child L of V, the descendents

An Introduction to Trees

Tree. A path is a connected sequence of edges. A tree topology is acyclic there is no loop.

CSI33 Data Structures

Binary Trees, Binary Search Trees

First Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms...

CS301 - Data Structures Glossary By

Trees! Ellen Walker! CPSC 201 Data Structures! Hiram College!

Chapter 4 Trees. Theorem A graph G has a spanning tree if and only if G is connected.

Recursive Data Structures and Grammars

Formal Languages and Automata Theory, SS Project (due Week 14)

Trees. Tree Structure Binary Tree Tree Traversals

Data Structures. Trees. By Dr. Mohammad Ali H. Eljinini. M.A. Eljinini, PhD

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

CS24 Week 8 Lecture 1

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305

Data Structures. Outline. Introduction Linked Lists Stacks Queues Trees Deitel & Associates, Inc. All rights reserved.

R13. II B. Tech I Semester Supplementary Examinations, May/June DATA STRUCTURES (Com. to ECE, CSE, EIE, IT, ECC)

Objective Questions for Online Practical Exams under CBCS Scheme Subject: Data Structure-I (CS-113)

March 20/2003 Jayakanth Srinivasan,

Name CPTR246 Spring '17 (100 total points) Exam 3

CSI33 Data Structures

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE

Garbage Collection: recycling unused memory

7.1 Introduction. A (free) tree T is A simple graph such that for every pair of vertices v and w there is a unique path from v to w

CS8391-DATA STRUCTURES QUESTION BANK UNIT I

Data Structures Question Bank Multiple Choice

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

The Stack and Queue Types

Trees. (Trees) Data Structures and Programming Spring / 28

Course Review for. Cpt S 223 Fall Cpt S 223. School of EECS, WSU

Binary Trees

Chapter 20: Binary Trees

Abstract Data Structures IB Computer Science. Content developed by Dartford Grammar School Computer Science Department

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours

3137 Data Structures and Algorithms in C++

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.

CS8391-DATA STRUCTURES

Data Structure. IBPS SO (IT- Officer) Exam 2017

CS 206 Introduction to Computer Science II

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

Computer Science 210 Data Structures Siena College Fall Topic Notes: Trees

F453 Module 7: Programming Techniques. 7.2: Methods for defining syntax

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

CS 8391 DATA STRUCTURES

ADTS, GRAMMARS, PARSING, TREE TRAVERSALS

Upcoming ACM Events Linux Crash Course Date: Time: Location: Weekly Crack the Coding Interview Date:

COMP 250 Fall binary trees Oct. 27, 2017

E.G.S. PILLAY ENGINEERING COLLEGE (An Autonomous Institution, Affiliated to Anna University, Chennai) Nagore Post, Nagapattinam , Tamilnadu.

Tree. Virendra Singh Indian Institute of Science Bangalore Lecture 11. Courtesy: Prof. Sartaj Sahni. Sep 3,2010

Basic Data Structures (Version 7) Name:

CE 221 Data Structures and Algorithms

1. Stack overflow & underflow 2. Implementation: partially filled array & linked list 3. Applications: reverse string, backtracking

CS 206 Introduction to Computer Science II

Data Abstractions. National Chiao Tung University Chun-Jen Tsai 05/23/2012

Binary Trees and Binary Search Trees

Lecture Notes 16 - Trees CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

CS W3134: Data Structures in Java

Programming II (CS300)

Friday, March 30. Last time we were talking about traversal of a rooted ordered tree, having defined preorder traversal. We will continue from there.

Section Summary. Introduction to Trees Rooted Trees Trees as Models Properties of Trees

Principles of Computer Science

Prepared By: Ms. Nidhi Solanki (Assist. Prof.) Page 1

Introduction to Computers and Programming. Concept Question

09 STACK APPLICATION DATA STRUCTURES AND ALGORITHMS REVERSE POLISH NOTATION

Department of Computer Science and Technology

Topic 14. The BinaryTree ADT

Programming II (CS300)

Data Structure - Binary Tree 1 -

Data Structure Advanced

CISC 235 Topic 3. General Trees, Binary Trees, Binary Search Trees

DEEPIKA KAMBOJ UNIT 2. What is Stack?

Binary Trees. Height 1

Algorithms and Data Structures

C Data Structures Stacks. Stack. push Adds a new node to the top of the stack

Topic Binary Trees (Non-Linear Data Structures)

Introduction to Binary Trees

Data Structures. 1. Each entry in a linked list is a called a (a)link (b)node (c)data structure (d)none of the above

Design and Analysis of Algorithms Lecture- 9: Binary Search Trees

6-TREE. Tree: Directed Tree: A directed tree is an acyclic digraph which has one node called the root node

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified)

8. Write an example for expression tree. [A/M 10] (A+B)*((C-D)/(E^F))

Table of Contents. Chapter 1: Introduction to Data Structures... 1

Trees. Truong Tuan Anh CSE-HCMUT

There are many other applications like constructing the expression tree from the postorder expression. I leave you with an idea as how to do it.

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

The Bucharest University of Economic Studies. Data Structures. ADTs-Abstract Data Types Stacks and Queues

MLR Institute of Technology

Chapter Summary. Introduction to Trees Applications of Trees Tree Traversal Spanning Trees Minimum Spanning Trees

University of Palestine. Final Exam 2 nd semester 2014/2015 Total Grade: 50

CSE 373 APRIL 17 TH TREE BALANCE AND AVL

Transcription:

Programming III Stacks, Queues and Hierarchical Collections 2501ICT Nathan Contents Linked Data Structures Revisited Stacks Queues Trees Binary Trees Generic Trees Implementations 2 Copyright 2002- by René Hexel. All rights reserved. 1

Programming III Queues and Stacks Linear Collections Can be implemented in different ways, e.g. Arrays Linked Lists Are often used in Operating Systems and run time environments Function/Method calling Stacks Process priority Queues Queues FIFO collections First element enqueued is first to be dequeued Insertions occur at one end, the rear Removals occur at the other end, the front Priority Queue Extensions Reordering according to priority Few priorities: multiple Queues Many priorities: insert according to priority 4 Copyright 2002- by René Hexel. All rights reserved. 2

Programming III Queues using Lists Use the head and tail Pointers head NULL front data rear tail NULL Enqueue: Insert from the tail (rear) Dequeue: Remove from the head (front) 5 Priority Queues Implementation #1: Multiple Lists One list per priority Enqueue on the corresponding list Dequeue starting at the highest priority list Go to next lower priority if empty, etc. Does not require search operation to enqueue Requires two pointers (head/tail) per priority: Faster enqueue, but slower dequeue operation Useful if number of different priorities is small 6 Copyright 2002- by René Hexel. All rights reserved.

Programming III Priority Queues (2) #2: Priority Ordering Only one list Enqueue according to priority Higher priority entries overtake lower ones Dequeue always from the head Requires linear search to enqueue: O(n) Dequeue doesn t require search: O(1) Useful if number of different priorities is large 7 Queue Applications First-Come-First Serve Algorithms OS Process Scheduling Event Handling Modelling and Simulation of Real- World Processes E.g. checkout queue in a supermarket 8 Copyright 2002- by René Hexel. All rights reserved. 4

Programming III Stacks LIFO collection The last element pushed onto the stack is the first to be retrieved Both push (insertion) and pop (deletion) operations occur at the top of the stack Implementation Arrays Singly linked lists 9 Array Implementation Index: i = 0; Push: stack[i] = element; Pop: element = stack[--i]; Peek: element = stack[i-1]; Sneak preview, without changing i Watch Preconditions! 10 Copyright 2002- by René Hexel. All rights reserved. 5

Programming III Stack Example Parsing Matching Parentheses expression = { letter } ( expression ) [ expression ] either a letter or an expression in brackets Legal examples a ab (a) (ab) [(a)] [a(b)cd] Illegal examples a) )( a( [[(]) [a)a] 11 Matching () Algorithm For each character c in the String If c is (, [, or { Push c onto the stack Else if c is ), ], or } If the stack is empty: return false Else pop the top opening bracket and check if it matches the corresponding closing bracket Return true if the stack is empty 12 Copyright 2002- by René Hexel. All rights reserved. 6

Programming III Hierarchical Collections Tree definition Types of Trees Binary Expressions Expression Trees Tree traversals: pre-, in-, postorder Examples Generating Postfix, Parsing 1 Tree Definition Each node has at most one predecessor Parent Many Successors Children Siblings D2 D1 D Nodes sharing the same parent (eg, D2 and D) 14 Copyright 2002- by René Hexel. All rights reserved. 7

Programming III Tree Definition (2) Topmost Node: root Successors Children, Children of Children Also called descendants All nodes are successors of root D2 D1 D4 D 15 Tree Definition () Leaf Nodes: Nodes without Successors E.g. D and D4 Frontier: The set of all leaf nodes D2 D1 D D4 16 Copyright 2002- by René Hexel. All rights reserved. 8

Programming III Tree Definition (4) Interior Nodes: Nodes with at least one successor E.g. D1 and D2 Ancestors: Immediate or indirect predecessors E.g, D1 is an ancestor of D2, D, and D4 D2 D1 D4 D 17 Tree Definition (5) Levels are numbered from 0 Level 0 is always the root This tree has Levels Level 0: D1 Level 1: D2 and D Level 2: D4 D2 D4 D1 D Level 0 Level 1 Level 2 18 Copyright 2002- by René Hexel. All rights reserved. 9

Programming III Binary Trees Binary Trees allow at most two children per Node Generic Trees allow any number of children per Node D2 D1 D4 D 19 Generic Trees Order of the Tree: Maximum Number of successors allowed for any given Node E.g., Order: Generic Trees are sometimes called General Trees D2 D1 D5 D4 D 20 Copyright 2002- by René Hexel. All rights reserved. 10

Programming III Tree Applications Parsing Languages Computer Languages, Mathematical Formula Natural Languages Searchable Data Structures Databases (e.g., B-Trees) Heaps and Balanced Trees Sorting and organising Data 21 Parsers Read in Expressions E.g., (2 ) * 5 Check Syntactical Correctness Is everything where it should be? Create Parse Tree Evaluator checks semantic meaning and processes the data in the Tree to produce meaningful output 22 Copyright 2002- by René Hexel. All rights reserved. 11

Programming III Binary Expressions Stored in Binary Trees: e.g. 5 Numbers Leaf Nodes Operators Interior Nodes Operands Contained in Subtree of the Expression 5 2 Example Expression * 4 5 * 5 4 24 Copyright 2002- by René Hexel. All rights reserved. 12

Programming III Example Expression (2) * (4 5) * 4 5 25 Operator Precedence * (4 5) * The higher the precedence, the lower in the tree! Overridden by parentheses! 4 5 26 Copyright 2002- by René Hexel. All rights reserved. 1

Programming III Operator Precedence (2) 4 5 If operators have equal precedence, the ones on the left appear lower in the tree when parsed from left to right! 4 5 27 Evaluating an Expression Tree Begin at the root Node If a number, return it, otherwise Run the operator w/ the results of Evaluating its left and right subtrees, and Return this value. 28 Copyright 2002- by René Hexel. All rights reserved. 14

Programming III Evaluating Example * (4 5) * 4 5 29 Evaluating Example (2) * (4 5) * * is an operator Evaluate left and right subtrees first! 4 5 0 Copyright 2002- by René Hexel. All rights reserved. 15

Programming III Evaluating Example () * (4 5) * is a number Return 4 5 1 Evaluating Example (4) * (4 5) * is an operator Evaluate left and right subtrees first! 4 5 2 Copyright 2002- by René Hexel. All rights reserved. 16

Programming III Evaluating Example (5) * (4 5) * 4 is a number Return 4 4 5 Evaluating Example (6) * (4 5) * 5 is a number Return 5 4 5 4 Copyright 2002- by René Hexel. All rights reserved. 17

Programming III Evaluating Example (7) * (4 5) * Add subtree results 9 Return 4 5 = 9 4 5 5 Evaluating Example (8) * (4 5) * 27 Multiply subtree results 9 Return * 9 = 27 4 5 6 Copyright 2002- by René Hexel. All rights reserved. 18

Programming III Evaluate Pseudocode evaluate(node) { if node is a number return number; else { left = evaluate(node.left); right = evaluate(node.right); return compute(node, left, right); } } 7 Binary Tree Traversals Preorder Visit node, then go left, then go right Inorder Go left, then visit node then go right Postorder: Depth First Go left, then go right, then visit node Breadth First Level 0, then Level 1, then Level 2, etc. 8 Copyright 2002- by René Hexel. All rights reserved. 19

Programming III Binary Tree Traversals (2) Preorder, Inorder, and Postorder Correspond with Prefix, Infix, and Postfix Notations of an Expression Infix: 5 Prefix = Polish Notation (PN) : (,5) Postfix = Reverse Polish Notation (RPN) : 5 Use the Same Generic Recursive Algorithm! 9 Prefix Pseudocode String prefix(node) { if (node == NULL) return ; else return node prefix(node.left) prefix (node.right); } 40 Copyright 2002- by René Hexel. All rights reserved. 20

Programming III Infix Pseudocode String infix(node) { if (node == NULL) return ; else return infix(node.left) node infix (node.right); } 41 Postfix Pseudocode String postfix(node) { if (node == NULL) return ; else return postfix(node.left) postfix (node.right) node; } 42 Copyright 2002- by René Hexel. All rights reserved. 21

Programming III A Binary Tree Structure @interface BTNode: NSObject; { BTNode *left; // left child BTNode *right; // right child id value; // the actual data } // here go the usual access methods: // -setleft, -setright, @end 4 A Binary Tree Constructor - initwithvalue: v left: (BTNode *) l right: (BTNode *) r { if (![self init]) return nil; value = v; left = l; right = r; return self; } 44 Copyright 2002- by René Hexel. All rights reserved. 22

Programming III Creating a Binary Tree BTNode *left = [[BTNode alloc] initwithvalue: @ left: nil right: nil]; nil nil 45 Creating a Binary Tree BTNode *left = [[BTNode alloc] initwithvalue: @ left: nil right: nil]; BTNode *right = [[BTNode alloc] initwithvalue: @ 5 left: nil right: nil]; 5 nil nil 46 Copyright 2002- by René Hexel. All rights reserved. 2

Programming III Creating a Binary Tree BTNode *left = [[BTNode alloc] initwithvalue: @ left: nil right: nil]; BTNode *right = [[BTNode alloc] initwithvalue: @ 5 left: nil right: nil]; BTNode *root = [[BTNode alloc] initwithvalue: @ left: left right: right]; 5 47 Creating a Binary Tree BTNode *left = [[BTNode alloc] initwithvalue: @ left: nil right: nil]; BTNode *right = [[BTNode alloc] initwithvalue: @ 5 left: nil right: nil]; BTNode *root = [[BTNode alloc] initwithvalue: @ left: left right: right]; Infix: 5 Postfix: 5 5 Prefix: (, 5) add(, 5) Functional notation 48 Copyright 2002- by René Hexel. All rights reserved. 24

Programming III Grammar Parsing Recursive Definition, e.g Infix: Expression = Term { - Term } Term = Factor { * / Factor } Factor = number ( Expression ) Represents standard math formulas, e.g. 4 * ( 5 - ( 6 / 7 ) ) Can be used to create a parse tree! 49 Recursive Descent Parsing Expression = Term { - Term } Term = Factor { * / Factor } Factor = number ( Expression ) Expression() { Term(); while (token == '' token == '-') { get_token(); Term(); } } 50 Copyright 2002- by René Hexel. All rights reserved. 25

Programming III Recursive Descent Parsing Expression = Term { - Term } Term = Factor { * / Factor } Factor = number ( Expression ) Term() { Factor(); while (token == '*' token == '/') { get_token(); Factor(); } } 51 Recursive Descent Parsing Expression = Term { - Term } Term = Factor { * / Factor } Factor = number ( Expression ) Factor() { switch (token) { case number: get_token(); break; case '(': get_token(); Expression(); if (token!= ')') error( No closing ')'"); get_token(); break; } } default: error(error '%s'\n", token); 52 Copyright 2002- by René Hexel. All rights reserved. 26

Programming III References Lambert, K. A., & Osborne, M. (2004): A Framework for Program Design and Data Structures: Brooks/Cole. Chapters 8-10 http://en.wikipedia.org/wiki/tree_data_structure http://en.wikipedia.org/wiki/binary_tree http://en.wikipedia.org/wiki/recursive_descent_parser http://mathworld.wolfram.com/weightedtree.html Week 6 example code: SimpleTree.zip 5 Appendix C Language Examples Copyright 2002- by René Hexel. All rights reserved. 27

Programming III A Binary Tree Structure (C) typedef struct BinTreeNode btnode; struct BinTreeNode { btnode *left; /* left child */ btnode *right; /* right child */ void *value; /* the actual data */ }; 55 A Binary Tree Constructor (C) btnode *newbtnode(void *data, btnode *left, btnode *right) { btnode *this = malloc(sizeof btnode); this->value = data; this->left = left; this->right = right; } return this; 56 Copyright 2002- by René Hexel. All rights reserved. 28

Programming III Creating a Binary Tree (C) btnode *left = newbtnode(, NULL, NULL); NULL NULL 57 Creating a Binary Tree (C) btnode *left = newbtnode(, NULL, NULL); btnode *right = newbtnode( 5, NULL, NULL); 5 NULL NULL 58 Copyright 2002- by René Hexel. All rights reserved. 29

Programming III Creating a Binary Tree (C) btnode *left = newbtnode(, NULL, NULL); btnode *right = newbtnode( 5, NULL, NULL); btnode *root = newbtnode(, left, right); 5 59 Creating a Binary Tree (C) btnode *left = newbtnode(, NULL, NULL); btnode *right = newbtnode( 5, NULL, NULL); btnode *root = newbtnode(, left, right); Infix: 5 Postfix: 5 Prefix: (, 5) add(, 5) Functional Notation 5 60 Copyright 2002- by René Hexel. All rights reserved. 0