Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Data Structures Dale Roberts, Lecturer Computer Science,

Slides:



Advertisements
Similar presentations
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
Advertisements

Chapter 6 Structures By C. Shing ITEC Dept Radford University.
Binary Trees CSC 220. Your Observations (so far data structures) Array –Unordered Add, delete, search –Ordered Linked List –??
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
CS 171: Introduction to Computer Science II
Lists A list is a finite, ordered sequence of data items. Two Implementations –Arrays –Linked Lists.
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (4) Data Structures 11/18/2008 Yang Song.
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
 2006 Pearson Education, Inc. All rights reserved Data Structures.
Important Problem Types and Fundamental Data Structures
CHAPTER 71 TREE. Binary Tree A binary tree T is a finite set of one or more nodes such that: (a) T is empty or (b) There is a specially designated node.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Abstract Data Types Dale Roberts, Lecturer
UNIT-2. Singly Linked List Doubly Linked List Circular Linked List Representing Stack with Linked List. Representing Queue with Linked List.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
Introduction to Data Structures Systems Programming.
ECE 103 Engineering Programming Chapter 61 Abstract Data Types Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material.
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Review of Recursion For those of you that have slept since.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
Data Structures Systems Programming. 22 Data Structures  Queues –Queuing System Models –Queue Data Structures –A Queue Example  Trees –Binary Trees.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
CSC 211 Data Structures Lecture 23
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Trees Dale Roberts, Lecturer
Introduction to Data Structures Systems Programming Concepts.
Slide 1 Linked Data Structures. Slide 2 Learning Objectives  Nodes and Linked Lists  Creating, searching  Linked List Applications  Stacks, queues.
Programming Practice 3 - Dynamic Data Structure
Copyright © 2002 Pearson Education, Inc. Slide 1.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Recursion and Trees Dale Roberts, Lecturer
Data Structures Systems Programming. Systems Programming: Data Structures 2 2 Systems Programming: 2 Data Structures  Queues –Queuing System Models –Queue.
Chapter 16 – Data Structures and Recursion. Data Structures u Built-in –Array –struct u User developed –linked list –stack –queue –tree Lesson 16.1.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Discrete Mathematics Chapter 5 Trees.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Elementary Data Structures Array Lists Array Lists Dale.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Elementary Data Structures Linked Lists Linked Lists Dale.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
Search: Binary Search Trees Dr. Yingwu Zhu. Review: Linear Search Collection of data items to be searched is organized in a list x 1, x 2, … x n – Assume.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
Data Structures - Prabir Sarkar. AGENDA Stack Queue Linked List Trees Graphs Searching and Sorting Algorithm.
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture13.
© Oxford University Press All rights reserved. Data Structures Using C, 2e Reema Thareja.
DATA STRUCURES II CSC QUIZ 1. What is Data Structure ? 2. Mention the classifications of data structure giving example of each. 3. Briefly explain.
Data Structure By Amee Trivedi.
Chapter 12 – Data Structures
5.13 Recursion Recursive functions Functions that call themselves
Top 50 Data Structures Interview Questions
12 C Data Structures.
12 C Data Structures.
Elementary Data Structures
Chapter 22 Custom Generic Data Structures
Trees.
Introduction to Data Structures
Binary Trees, Binary Search Trees
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Review & Lab assignments
Binary Trees, Binary Search Trees
Binary Trees, Binary Search Trees
NATURE VIEW OF A TREE leaves branches root. NATURE VIEW OF A TREE leaves branches root.
Presentation transcript:

Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Data Structures Dale Roberts, Lecturer Computer Science, IUPUI

Dale Roberts Data Structure Algorithms deals with the manipulation of data Data structure deals with the organization of data Algorithms + Data Structures = Programs Suppose we have a list of sorted data on which we have to perform the following operations: Search for an item delete a specified item insert (add) a specified item Example: suppose we begin with the following list: data: location: What is a list? A list is a data structure where data is represented linearly. A list can be implemented using arrays on a machine. Finite sequence of items from the same data type Stored contiguously in the memory

Dale Roberts Example: suppose we begin with the following list: data: location: Now, delete item 358 from the above list Q:What is the algorithm to delete an item? Q: What is the cost of deleting an item? data: location: Q: When we delete 358, what happens to that location? Now, add item 498 onto the above list Q:Where would that item go? data: location: Q: What is the cost of inserting an item? Conclusion: Using a list representation of data, what is the overall efficiency of searching, adding, and deleting items? 498

Dale Roberts Linked Representation of Data In a linked representation, data is not stored in a contiguous manner. Instead, data is stored at random locations and the current data location provides the information regarding the location of the next data. Adding item 498 on to the linked list Q: What is the cost of adding an item? Q: how about adding 300 and 800 onto the linked list Deleting item 358 from the linked list Q: What is the cost of deleting an item? Q: What is the cost of searching for an item?

Dale Roberts Deletion of an Element from a List Algorithm: 1. locate the element in the list (this involves searching) 2. delete the element 3. reorganize the list and index Example: data: location: Delete 358 from the above list: 1. Locate 358:if we use ‘linear search’, we’ll compare 358 with each element of the list starting from the location Delete 358: remove it from the list data: location: Reorganize the list: move the remaining elements. data: location:

Dale Roberts Insertion of an Element in List Algorithm: 1. locate the position where the element in to be inserted (position may be user-specified in case of an unsorted list or may be decided by search for a sorted list) 2. reorganize the list and create an ‘empty’ slot 3. insert the element Example: (sorted list) data: location: Insert 505 onto the above list: 1. Locate the appropriate position by performing a binary search. 505 should be stored in location Create an ‘empty’ slot data: location: location: Insert 505 data: location:

Dale Roberts Introduction Dynamic data structures Data structures that grow and shrink during execution Linked lists Allow insertions and removals anywhere Stacks Allow insertions and removals only at top of stack Queues Allow insertions at the back and removals from the front Binary trees High-speed searching and sorting of data and efficient elimination of duplicate data items

Dale Roberts Linked Lists Linked list Linear collection of self-referential class objects, called nodes Connected by pointer links Accessed via a pointer to the first node of the list Subsequent nodes are accessed via the link-pointer member of the current node Link pointer in the last node is set to null to mark the list’s end Use a linked list instead of an array when You have an unpredictable number of data elements Your list needs to be sorted quickly

Dale Roberts Linked List How do we represent a linked list in the memory we use pointers to point to the next data item. Each location has two fields: Data Field and Pointer (Link) Field. Linked List Implementation struct node { int data; struct node *link; }; struct node my_node; Example: START Node Element Pointer (Link) Field Data Field Null Pointer NULL

Dale Roberts Self-Referential Structures Self-referential structures Structure that contains a pointer to a structure of the same type Can be linked together to form useful data structures such as lists, queues, stacks and trees Terminated with a NULL pointer ( 0 ) Diagram of two self-referential structure objects linked together struct node { int data; struct node *nextPtr; } nextPtr Points to an object of type node Referred to as a link Ties one node to another node 100 NULL pointer (points to nothing)Data member and pointer 500 … 32

Dale Roberts Linked Lists Types of linked lists: Singly linked list Begins with a pointer to the first node Terminates with a null pointer Only traversed in one direction Circular, singly linked Pointer in the last node points back to the first node Doubly linked list Two “start pointers” – first element and last element Each node has a forward pointer and a backward pointer Allows traversals both forwards and backwards Circular, doubly linked list Forward pointer of the last node points to the first node and backward pointer of the first node points to the last node

Dale Roberts Linked List Manipulation Algorithms List Traversal Let START be a pointer to a linked list in memory. Write an algorithm to print the contents of each node of the list Algorithm 1. set PTR = START 2. repeat step 3 and 4 while PTR  NULL 3. print PTR->DATA 4. set PTR = PTR -> LINK 5. stop 1000 START PTR PTR = LINK[PTR] DataLink

Dale Roberts /* basic link list application */ /* forward order */ #define NULL 0 struct list { int data; struct list *next; } typedef struct list node; typedef node *link; main(){ link ptr, head; int num, i; head = (link)malloc(sizeof(node)); ptr=head; printf(“input 5 different data\n”); /* construct a linked list */ for (i=0; i<5; i++) { scanf(“%d”,&num); ptr->data = num; ptr->next=(link)malloc(sizeof(node));ptr=ptr->next;} ptr=NULL; /* List Traversal */ printf(“sequential print of the list\n”); ptr=head; while (ptr->next != NULL) { printf(“The value is: %d\n”, ptr->data); ptr=ptr->next; } input 5 different data sequential print of the list The value is: 5 The value is: 4 The value is: 3 The value is: 2 The value is: 9

Dale Roberts /* basic link list application */ /* reverse order */ #define NULL 0 struct list { int data; struct list *next; } typedef struct list node; typedef node *link; main(){ link ptr, tail, head; int num, i; tail = (link)malloc(sizeof(node)); tail->next = NULL; ptr=tail; printf(“input 5 different data\n”); /* construct a linked list */ for (i=0; i<5; i++) { scanf(“%d”,&num); ptr->data = num; head =(link)malloc(sizeof(node)); head->next = ptr; ptr = head; } ptr=ptr->next; /* List Traversal */ printf(“reverse print of the list\n”); while (ptr->next != NULL) { printf(“The value is: %d\n”, ptr->data); ptr=ptr->next; } input 5 different data sequential print of the list The value is: 9 The value is: 2 The value is: 3 The value is: 4 The value is: 5

Dale Roberts Search for a ITEM Let START be a pointer to a linked list in memory. Write an algorithm that finds the location LOC of the node where ITEM first appears in the list, or sets LOC=NULL if search is unsuccessful. Algorithm 1. set PTR = START 2. repeat step 3 while PTR  NULL 3. if ITEM == PTR -> DATA, then 4. set LOC = PTR, and Exit 5. else 6. set PTR = PTR -> LINK 7. set LOC = NULL /*search unsuccessful */ 8. Stop 1000 START PTR PTR = LINK[PTR]

Dale Roberts Insertion into a Listed List Let START be a pointer to a linked list in memory with successive nodes A and B. Write an algorithm to insert node N between nodes A and B. Algorithm 1. Set PTR = START 2. Repeat step 3 while PTR  NULL 3. If PTR == A, then 4. Set N->LINK = PTR -> LINK (or = B) 5. Set PTR->LINK = N 6. exit 7. else 8. Set PTR=PTR->LINK 9. If PTR == NULL insertion unsuccessful 10. Stop START Node ANode B PTR START Node ANode B 3500 Node N 3 cases: first node, last node, in-between node. ( ex: if ITEM = 500? if ITEM = 6000?)

Dale Roberts Deletion from a Linked List Let START be a pointer to a linked list in memory that contains integer data. Write an algorithm to delete note which contains ITEM. Algorithm 1. Set PTR=START and TEMP = START 2. Repeat step 3 while PTR  NULL 3. If PTR->DATA == ITEM, then 4. Set TEMP->LINK = PTR -> LINK, exit 5. else 6. TEMP = PTR 7. PTR = PTR -> LINK 8. Stop 3 cases: first node, last node, in-between node. ( ex: if ITEM = 1000? if ITEM = 5000?) PTR START Node ANode B 3500 Node N START Node ANode B 3500 Node N 3500 ITEM ….. TEMP

Dale Roberts 1/* Fig. 12.3: fig12_03.c 2 Operating and maintaining a list */ 3#include 4#include 5 6struct listNode { /* self-referential structure */ 7 char data; 8 struct listNode *nextPtr; 9}; 10 11typedef struct listNode ListNode; 12typedef ListNode *ListNodePtr; 13 14void insert( ListNodePtr *, char ); 15char delete( ListNodePtr *, char ); 16int isEmpty( ListNodePtr ); 17void printList( ListNodePtr ); 18void instructions( void ); 19 20int main() 21{ 22 ListNodePtr startPtr = NULL; 23 int choice; 24 char item; 25 Define struct Function prototypes Initialize variables Abstract Data Type

Dale Roberts while ( choice != 3 ) { switch ( choice ) { 33 case 1: 34 printf( "Enter a character: " ); 35 scanf( "\n%c", &item ); 36 insert( &startPtr, item ); 37 printList( startPtr ); 38 break; 39 case 2: 40 if ( !isEmpty( startPtr ) ) { 41 printf( "Enter character to be deleted: " ); 42 scanf( "\n%c", &item ); if ( delete( &startPtr, item ) ) { 45 printf( "%c deleted.\n", item ); 46 printList( startPtr ); 47 } 48 else 49 printf( "%c not found.\n\n", item ); 50 } 51 else 52 printf( "List is empty.\n\n" ); break; 26 instructions(); /* display the menu */ 27 printf( "? " ); 28 scanf( "%d", &choice ); Input choice switch statement

Dale Roberts printf( "? " ); 62 scanf( "%d", &choice ); 63 } printf( "End of run.\n" ); 66 return 0; 67} 68 69/* Print the instructions */ 70void instructions( void ) 71{ 72 printf( "Enter your choice:\n" 73 " 1 to insert an element into the list.\n" 74 " 2 to delete an element from the list.\n" 75 " 3 to end.\n" ); 76} default: 56 printf( "Invalid choice.\n\n" ); 57 instructions(); 58 break; 59 }

Dale Roberts while ( currentPtr != NULL && value > currentPtr->data ) { 93 previousPtr = currentPtr; /* walk to... */ 94 currentPtr = currentPtr->nextPtr; /*... next node */ 95 } if ( previousPtr == NULL ) { 98 newPtr->nextPtr = *sPtr; 99 *sPtr = newPtr; 100 } 101 else { 102 previousPtr->nextPtr = newPtr; 103 newPtr->nextPtr = currentPtr; 104 } 105 } 106 else 107 printf( "%c not inserted. No memory available.\n", value ); 108 } /* Insert a new value into the list in sorted order */ 79void insert( ListNodePtr *sPtr, char value ) 80{ 81 ListNodePtr newPtr, previousPtr, currentPtr; newPtr = malloc( sizeof( ListNode ) ); if ( newPtr != NULL ) { /* is space available */ 86 newPtr->data = value; 87 newPtr->nextPtr = NULL; previousPtr = NULL; 90 currentPtr = *sPtr;

Dale Roberts 133 free( tempPtr ); 134 return value; 135 } 136 } return '\0'; 139 } else { 122 previousPtr = *sPtr; 123 currentPtr = ( *sPtr )->nextPtr; while ( currentPtr != NULL && currentPtr->data != value ) { 126 previousPtr = currentPtr; /* walk to... */ 127 currentPtr = currentPtr->nextPtr; /*... next node */ 128 } if ( currentPtr != NULL ) { 131 tempPtr = currentPtr; 132 previousPtr->nextPtr = currentPtr->nextPtr; 110 /* Delete a list element */ 111 char delete( ListNodePtr *sPtr, char value ) 112 { 113 ListNodePtr previousPtr, currentPtr, tempPtr; if ( value == ( *sPtr )->data ) { 116 tempPtr = *sPtr; 117 *sPtr = ( *sPtr )->nextPtr; /* de-thread the node */ 118 free( tempPtr ); /* free the de-threaded node */ 119 return value; 120 }

Dale Roberts while ( currentPtr != NULL ) { 156 printf( "%c --> ", currentPtr->data ); 157 currentPtr = currentPtr->nextPtr; 158 } printf( "NULL\n\n" ); 161 } 162} 151 printf( "List is empty.\n\n" ); 152 else { 153 printf( "The list is:\n" ); 147 /* Print the list */ 148 void printList( ListNodePtr currentPtr ) 149 { 150 if ( currentPtr == NULL ) 141 /* Return 1 if the list is empty, 0 otherwise */ 142 int isEmpty( ListNodePtr sPtr ) 143 { 144 return sPtr == NULL; 145 } 146 Enter your choice: 1 to insert an element into the list. 2 to delete an element from the list. 3 to end. ? 1 Enter a character: B The list is: B --> NULL ? 1 Enter a character: A The list is: A --> B --> NULL ? 1 Enter a character: C The list is: A --> B --> C --> NULL ? 2 Enter character to be deleted: D D not found. ? 2 Enter character to be deleted: B B deleted. The list is: A --> C --> NULL Program Output:

Dale Roberts Trees Definitions Tree: A tree is a collection of nodes. If the collection is not empty, it must consist of a unique root node, r, and zero or more nonempty subtrees T 1, T 2,…, T k, with roots connected by a direct edge from r For a tree of N nodes, there must be N-1 edges. A node with no child is called a leaf node; nodes with the same parents are siblings. A E C D G F I H B M L K J N P Q –Path: a path from node n 1 to n k is a sequence of nodes n 1, n 2, …, n k such that n i is the parent of n i+1 (1  i  k); The no. of edges in the path is call the length of the path; A length 0 path is a path from a node to itself. There is a unique path from root to any node n i ; The length of this path is called the depth of n i ; thus, the root is a depth 0 node. –The height of a node n i is the length of the longest path from n i to a leaf node, thus, the height of a leaf node is 0. –The height of a tree is the height of its root node. The depth of a tree is the depth of the deepest leaf node, which is the same as the height of the tree.

Dale Roberts Tree Terminology (Review) Height – deepest level, not including root. Leaf nodes – have no children Interior Notes – have at least one child Degree of a node – Number of children In a binary tree, interior nodes have degree 1 or 2.

Dale Roberts Binary trees –Definition: A binary tree is a tree in which no nodes can have more than two children. –The root node is the first node in a tree. –Each link in the root node refers to a child –A node with no children is called a leaf node –Total number of nodes in a full binary tree of height k is 2 k -1 –Implementation Struct BinaryNode { data_type element; BinaryNode  left; BinaryNode  right; } Binary Trees B A D C

Dale Roberts Binary Tree Binary tree has interior nodes restricted to degree 1 or 2.

Dale Roberts Array implementation of binary tree We can embed the nodes of a binary tree into a one-dimensional array by defining a relationship between the position of each parent node and the position of its children. 1. left_child of node i is 2*i 1. left_child of node i is 2*i 2. right_child of node i is 2*i+1 2. right_child of node i is 2*i+1 3. parent of node i is i/2 (integer division) 3. parent of node i is i/2 (integer division) How much space is required for the array to represent a tree of depth d? 2 d+1 – 1 (must assume full tree)

Dale Roberts Dynamic Implementation of Binary Tree A dynamic implementation of a binary tree uses space proportional to the actual number of nodes used. Not the size of the full tree. Struct BinaryNode { data_type element; BinaryNode  left; BinaryNode  right; }

Dale Roberts Binary search tree (BST) Values in left subtree less than parent Values in right subtree greater than parent Facilitates duplicate elimination Fast searches - for a balanced tree, maximum of log 2 (n) comparisons Construct a BST from the values: 47, 25, 77, 11, 43, 65, 93, 7, 17, 31, 44, 68 Binary Search Tree (BST)

Dale Roberts Binary Search Tree (BST) Question: Construct an Binary Search Tree (BST) for the data Array Implementation:

Dale Roberts Binary Trees Tree traversals: In-order traversal – prints the node values in ascending order (LNR) 1. Traverse the left sub-tree with an in-order traversal 2. Process the value in the node (i.e., print the node value) 3. Traverse the right sub-tree with an in-order traversal Pre-order traversal (NLR) 1. Process the value in the node 2. Traverse the left sub-tree with a preorder traversal 3. Traverse the right sub-tree with a preorder traversal Post-order traversal (LRN) 1. Traverse the left sub-tree with a post-order traversal 2. Traverse the right sub-tree with a post-order traversal 3. Process the value in the node

Dale Roberts Tree Traversal is “Naturally” recursive Naturally recursive because: 1. Subgraphs are similar in character to the original graph. 2. Subgraphs are smaller. 3. Guaranteed to eventually hit a leaf (acyclic is assumed) Obeys fundamental rules of recursion 1.) Base cases 2.) Makes progress through recursion 3.) Assume recursive calls work (abstraction) Always specify the base case; otherwise, infinite recursive will occur and cause “stack-overflow” error.

Dale Roberts Sample recursive programs In-order: (LNR) void inorder(tree_pointer ptr) { if (ptr) if (ptr) { inorder(ptr->left_child); inorder(ptr->left_child); printf(“%d”, ptr->data); printf(“%d”, ptr->data); inorder(ptr->right_child); inorder(ptr->right_child); }} Pre-order: (NLR) void preorder(tree_pointer ptr) { if (ptr) if (ptr) { printf(“%d”, ptr->data); printf(“%d”, ptr->data); preorder(ptr->left_child); preorder(ptr->left_child); preorder(ptr->right_child); preorder(ptr->right_child); }} Post-order: (LRN) void postorder(tree_pointer ptr) { if (ptr) if (ptr) { postorder(ptr->left_child); postorder(ptr->left_child); postorder(ptr->right_child); postorder(ptr->right_child); printf(“%d”, ptr->data); printf(“%d”, ptr->data); }}

Dale Roberts Example: Expression Tree Example: An Expression Tree 1. Perform in-order traversal (LNR) A – B + C * E / F 2. Perform post-order traversal (LRN) A B – C E F / * + 3. Perform pre-order traversal (NLR) + - A B * C / E F + -* AB C / E F

Dale Roberts Tree Traversal Example Try your hand at traversing this tree: In-order: (LNR) Pre-order: (NLR) Post-order: (LRN) Apr, Aug, Dec, Feb, Jan, Jun, Jan, Mar, May, Nov, Oct, Sep Mar, Apr, Jul, Feb, Dec, Aug, Jun, Jan, May, Sep, Oct, Nov Aug, Dec, Jan, Jun, Feb, Jul, Apr, Nov, Oct, Sep, May, Mar

Dale Roberts Stack model A stack is a list with the restriction that insertion & deletion can be performed only at the end (or top) of the list. Only the top node is accessible: New nodes can be added and removed only at the top Similar to a pile of dishes Last-in, first-out (LIFO) Bottom of stack indicated by a link member to NULL Constrained version of a linked list push Adds a new node to the top of the stack pop Removes a node from the top Stores the popped value Returns true if pop was successful A stack can be empty, “pop” from an empty stack is an error A stack can never be full (assuming infinite memory) top S4 S3 S2 S1 top  Push (4)  Pop (4) top Stacks

Dale Roberts Stack Operations struct list { int data struct list *next; } typedef struct list node; typedef node *link; Push link push(link stack, int value) { link newnode; newnode = (link)malloc(sizeof(node)); newnode->data = value; newnode->next = stack; stack = newnode; return(stack);}Pop link pop(link stack, int *valuePtr) { link top; top = stack; stack = stack->next; *valuePtr = top->data; free(top);return(stack);} stack top stack top stack newnode stack newnode valuePtr 4

Dale Roberts Queues Queue Similar to a supermarket checkout line First-in, first-out (FIFO) Nodes are removed only from the head Nodes are inserted only at the tail Insert and remove operations Enqueue (insert) and dequeue (remove) Queue Model queue is a list, with insertion done only at one end and deletion done at the other end. enqueue: insert an element at the end of the queue dequeue: delete (and return) the element at the start of the queue first in first out model (FIFO) Linked list implementation of queues operating as a list constant time for enqueue & dequeue (keeping pointer to both the head and tail of the list)

Dale Roberts Queue Operations enqueue link enqueue(link queue, int value) { link newnode; newnode = (link)malloc(sizeof(node)); newnode->data = value; newnode->next = NULL; if (queue!=NULL) { queue->next = newnode; queue = queue->next; }else return(queue);}dequeue link dequeue(link queue, int *valuePtr) { link dequeuenode; dequeuenode = queue; *valuePtr = dequeuenode ->data; queue = queue->next; free(dequeuenode);return(queue);} newnodequeue