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