1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 18: Stacks And Queues.
Advertisements

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.
1 Linked List (II) Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures Series.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 15 – Data Structures Outline 15.1Introduction 15.2Self-Referential Classes 15.3Dynamic Memory.
 2009 Pearson Education, Inc. All rights reserved Data Structures Many slides modified by Prof. L. Lilien (even many without an explicit message).
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
 2006 Pearson Education, Inc. All rights reserved Data Structures.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 - Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory.
 2006 Pearson Education, Inc. All rights reserved Data Structures.
Linked List (I) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
Helpful C++ Transitions
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Trees.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
 2003 Prentice Hall, Inc. All rights reserved Linked Lists Upcoming program has two class templates –Create two class templates –ListNode data.
Templates Zhen Jiang West Chester University
Data Structures Outline Introduction Self-Referential Classes Dynamic Memory Allocation Linked Lists Stacks Queues Trees.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
 2006 Pearson Education, Inc. All rights reserved Data Structures.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
 Pearson Education, Inc. All rights reserved Data Structures.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templatized Tree.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 22 November 17, 2009.
Pointers & Dynamic Data Structures Chapter Dynamic Data Structures t Arrays & structs are static (compile time) t Dynamic expand as program executes.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 19 – Data Structures Outline 19.1 Introduction 19.2 Self-Referential Classes 19.3 Dynamic Memory.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Course Review FINAL.
Slide 1 Linked Data Structures. Slide 2 Learning Objectives  Nodes and Linked Lists  Creating, searching  Linked List Applications  Stacks, queues.
1 Chapter 17 – Data Structures Outline Introduction Self-Referential Classes Dynamic Memory Allocation Linked Lists Stacks Queues Trees.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 17 - Data Structures Outline 17.1 Introduction 17.2 Self-Referential Classes 17.3 Dynamic Memory.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Templates Lecture 10 March 23, 2004.
Programming Practice 3 - Dynamic Data Structure
Copyright © 2002 Pearson Education, Inc. Slide 1.
Data Structures Systems Programming. Systems Programming: Data Structures 2 2 Systems Programming: 2 Data Structures  Queues –Queuing System Models –Queue.
Final Exam –Date: Aug 27 th –Time: 9:00am – 12:00pm –Location: TEL 0014.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templatized Stack.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
 2003 Prentice Hall, Inc. All rights reserved. 1 Lecture 6: Classes and Data Abstraction Posted Feb 3 Chapter 6 pointer for function Class Introduction.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 20 November 10, 2009.
 2003 Prentice Hall, Inc. All rights reserved Stacks Upcoming program –Create stack from list insertAtFront, removeFromFront –Software reusability.
Data Structures - Prabir Sarkar. AGENDA Stack Queue Linked List Trees Graphs Searching and Sorting Algorithm.
CS 240Chapter 10 – TreesPage Chapter 10 Trees The tree abstract data type provides a hierarchical to the representation of certain types of relationships.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 20: Binary Trees.
Chapter 20 Custom Templatized Data Structures
Data Structure By Amee Trivedi.
Chapter 12 – Data Structures
12 C Data Structures.
12 C Data Structures.
Chapter 22 Custom Generic Data Structures
CISC181 Introduction to Computer Science Dr
Intro to Data Structures
Chapter 20: Binary Trees.
Helpful C++ Transitions
Chapter 21: Binary Trees.
Chapter 19 – Data Structures
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
20.5 Stacks Upcoming program Create stack from list
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Pointers & Dynamic Data Structures
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 20 - Data Structures
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
21 Data Structures.
Presentation transcript:

1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology

2 Chapter 17 - Data Structures Outline 17.1 Introduction 17.2 Self-Referential Classes 17.3 Dynamic Memory Allocation and Data Structures 17.4 Linked Lists 17.5 Stacks 17.6 Queues 17.7 Trees

Introduction Fixed-size data structures –Arrays, structs Dynamic data structures –Grow and shrink as program runs –Linked lists Insert/remove items anywhere –Stacks Insert/remove from top of stack –Queues Like a line, insert at back, remove from front –Binary trees High-speed searching/sorting of data

Self-Referential Classes Self-referential class –Has pointer to object of same class –Link together to form useful data structures Lists, stacks, queues, trees –Terminated with NULL pointer 1510

Self-Referential Classes Sample code class Node { public: Node( int ); void setData( int ); int getData() const; void setNextPtr( Node * ); const Node *getNextPtr() const; private: int data; Node *nextPtr; }; Pointer to object called a link –nextPtr points to a Node Class Node - int data; - NODE *nextPtr; Node

Dynamic Memory Allocation and Data Structures Dynamic memory allocation –Obtain and release memory during program execution –Create and remove nodes Operator new –Takes type of object to create –Returns pointer to newly created object Node *newPtr = new Node( 10 ); Returns bad_alloc if not enough memory 10 is the node's object data

Dynamic Memory Allocation and Data Structures Operator delete –delete newPtr; –Deallocates memory allocated by new, calls destructor –Memory returned to system, can be used in future newPtr not deleted, only the space it points to

Linked Lists Linked list –Collection of self-referential class objects (nodes) connected by pointers (links) –Accessed using pointer to first node of list Subsequent nodes accessed using the links in each node –Link in last node is null (zero) Indicates end of list –Data stored dynamically Nodes created as necessary Node can have data of any type

Linked Lists H D Q firstPtrlastPtr...

Linked Lists Linked lists vs. arrays –Arrays can become full Allocating "extra" space in array wasteful, may never be used Linked lists can grow/shrink as needed Linked lists only become full when system runs out of memory –Linked lists can be maintained in sorted order Insert element at proper position Existing elements do not need to be moved

Linked Lists Selected linked list operations –Insert node at front –Insert node at back –Remove node from front –Remove node from back In following illustrations –List has firstPtr and lastPtr –(a) is before, (b) is after

12 Insert at front 7 11 firstPtr 12 newPtr a) 711 firstPtr 12 newPtr b) newPtr->nextPtr = firstPtr firstPtr = newPtr If list empty, then firstPtr = lastPtr = newPtr

13 Insert at back firstPtrlastPtr a) newPtr firstPtrlastPtr b) newPtr lastPtr->nextPtr = newPtr lastPtr = newPtr If list empty, then firstPtr = lastPtr = newPtr

14 Remove from front firstPtrlastPtr a) firstPtrlastPtr b) tempPtr tempPtr = firstPtr firstPtr = firstPtr->next If there are no more nodes, firstPtr = lastPtr = 0 delete tempPtr

15 Remove from back firstPtrlastPtr a) firstPtrlastPtr b) tempPtr currentPtr 11 tempPtr = lastPtr "Walk" list until get next-to-last node, until currentPtr->nextPtr = lastPtr lastPtr = currentPtr delete tempPtr

Linked Lists Upcoming program has two class templates –Create two class templates –ListNode data (type depends on class template) nextPtr –List Linked list of ListNode objects List manipulation functions –insertAtFront –insertAtBack –removeFromFront –removeFromBack datanextPrt ListNode

17 1 // Fig. 17.3: listnode.h 3 #ifndef LISTNODE_H 4 #define LISTNODE_H 6 // forward declaration of class List 7 template class List; 9 template 10 class ListNode { 11 friend class List ; // make List a friend 13 public: 14 ListNode( const NODETYPE & ); // constructor 15 NODETYPE getData() const; // return data in node 17 private: 18 NODETYPE data; // data 19 ListNode *nextPtr; // next node in list 21 }; 24 template 25 ListNode ::ListNode( const NODETYPE &info ) 26 : data( info ), nextPtr( 0 ) { 31 } 34 template 35 NODETYPE ListNode ::getData() const { 37 return data; 39 } 41 #endif Class ListNode - NODETYPE data; - ListNode *nextPtr; NODETYPE ListNode

18 1 // Fig. 17.4: list.h 3 #ifndef LIST_H 4 #define LIST_H 10 #include 11 #include "listnode.h" 13 template 14 class List { 16 public: 17 List(); 18 ~List(); 19 void insertAtFront( const NODETYPE & ); 20 void insertAtBack( const NODETYPE & ); 21 bool removeFromFront( NODETYPE & ); 22 bool removeFromBack( NODETYPE & ); 23 bool isEmpty() const; 24 void print() const; 26 private: 27 ListNode *firstPtr; 28 ListNode *lastPtr; 31 ListNode *getNewNode( const NODETYPE & ); 33 }; 36 template 37 List ::List() 38 : firstPtr( 0 ), lastPtr( 0 ) { 43 } Class List - ListNode *firstPtr; - ListNode *lastPtr; NODETYPE firstPtrlastPtr +void insertAtFront( const NODETYPE & ); +void insertAtBack( const NODETYPE & ); +bool removeFromFront( NODETYPE & ); +bool removeFromBack( NODETYPE & ); +bool isEmpty() const; +void print() const;

19 46 template 47 List ::~List() { 49 if ( !isEmpty() ) { 50 cout << "Destroying nodes...\n"; 52 ListNode *currentPtr = firstPtr; 53 ListNode *tempPtr; 55 while ( currentPtr != 0 ) { 56 tempPtr = currentPtr; 57 cout data << '\n'; 58 currentPtr = currentPtr->nextPtr; 59 delete tempPtr; 61 } 63 } 65 cout << "All nodes destroyed\n\n"; 67 } 70 template 71 void List ::insertAtFront( const NODETYPE &value ) { 73 ListNode *newPtr = getNewNode( value ); 75 if ( isEmpty() ) 76 firstPtr = lastPtr = newPtr; 78 else { 79 newPtr->nextPtr = firstPtr; 80 firstPtr = newPtr; 82 } 84 } ListNode Class List - ListNode *firstPtr; - ListNode *lastPtr; NODETYPE firstPtrlastPtr ListNode tempPtr currentPtr ListNode firstPtrlastPtr ListNode newPtr currentPtr ListNode

20 87 template 88 void List ::insertAtBack( const NODETYPE &value ) { 90 ListNode *newPtr = getNewNode( value ); 92 if ( isEmpty() ) 93 firstPtr = lastPtr = newPtr; 95 else { 96 lastPtr->nextPtr = newPtr; 97 lastPtr = newPtr; 99 } 101 } 104 template 105 bool List ::removeFromFront( NODETYPE &value ) { 107 if ( isEmpty() ) 108 return false; 110 else { 111 ListNode *tempPtr = firstPtr; 113 if ( firstPtr == lastPtr ) 114 firstPtr = lastPtr = 0; 115 else 116 firstPtr = firstPtr->nextPtr; 118 value = tempPtr->data; 119 delete tempPtr; 121 return true; 123 } 125 } ListNode firstPtrlastPtr ListNode newPtr ListNode firstPtrlastPtr ListNode tempPtr

template 129 bool List ::removeFromBack( NODETYPE &value ) { 131 if ( isEmpty() ) 132 return false; 134 else { 135 ListNode *tempPtr = lastPtr; 137 if ( firstPtr == lastPtr ) 138 firstPtr = lastPtr = 0; 139 else { 140 ListNode *currentPtr = firstPtr; 143 while ( currentPtr->nextPtr != lastPtr ) 144 currentPtr = currentPtr->nextPtr; 146 lastPtr = currentPtr; 147 currentPtr->nextPtr = 0; 149 } 151 value = tempPtr->data; 152 delete tempPtr; 154 return true; 156 } 158 } 161 template 162 bool List ::isEmpty() const { 164 return firstPtr == 0; 166 } ListNode firstPtrlastPtr ListNode tempPtrcurrentPtr

template 170 ListNode *List ::getNewNode( 171 const NODETYPE &value ) { 173 return new ListNode ( value ); 175 } 178 template 179 void List ::print() const{ 181 if ( isEmpty() ) { 182 cout << "The list is empty\n\n"; 183 return; 185 } 187 ListNode *currentPtr = firstPtr; 189 cout << "The list is: "; 191 while ( currentPtr != 0 ) { 192 cout data << ' '; 193 currentPtr = currentPtr->nextPtr; 195 } 197 cout << "\n\n"; 199 } 201 #endif

23 1 // Fig. 17.5: fig17_05.cpp 8 #include 10 using std::string; 12 #include "list.h" 15 template 16 void testList( List &listObject, const string &typeName ) { 18 cout << "Testing a List of " << typeName << " values\n"; 20 instructions(); 22 int choice; 23 T value; 25 do { 26 cout << "? "; 27 cin >> choice; 29 switch ( choice ) { 30 case 1: 31 cout << "Enter " << typeName << ": "; 32 cin >> value; 33 listObject.insertAtFront( value ); 34 listObject.print(); 35 break; 37 case 2: 38 cout << "Enter " << typeName << ": "; 39 cin >> value; 40 listObject.insertAtBack( value ); 41 listObject.print(); 42 break;

24 44 case 3: 45 if ( listObject.removeFromFront( value ) ) 46 cout << value << " removed from list\n"; 48 listObject.print(); 49 break; 51 case 4: 52 if ( listObject.removeFromBack( value ) ) 53 cout << value << " removed from list\n"; 55 listObject.print(); 56 break;} 60 } while ( choice != 5 ); 62 cout << "End list test\n\n"; 64 } 67 void instructions() { 69 cout << "Enter one of the following:\n" 70 << " 1 to insert at beginning of list\n" 71 << " 2 to insert at end of list\n" 72 << " 3 to delete from beginning of list\n" 73 << " 4 to delete from end of list\n" 74 << " 5 to end list processing\n"; 76 } 78 int main() { 81 List integerList; 82 testList( integerList, "integer" ); 85 List doubleList; 86 testList( doubleList, "double" );}

25 Testing a List of integer values Enter one of the following: 1 to insert at beginning of list 2 to insert at end of list 3 to delete from beginning of list 4 to delete from end of list 5 to end list processing ? 1 Enter integer: 1 The list is: 1 ? 1 Enter integer: 2 The list is: 2 1 ? 2 Enter integer: 3 The list is: ? 2 Enter integer: 4 The list is:

26 ? 3 2 removed from list The list is: ? 3 1 removed from list The list is: 3 4 ? 4 4 removed from list The list is: 3 ? 4 3 removed from list The list is empty ? 5 End list test

27 Testing a List of double values Enter one of the following: 1 to insert at beginning of list 2 to insert at end of list 3 to delete from beginning of list 4 to delete from end of list 5 to end list processing ? 1 Enter double: 1.1 The list is: 1.1 ? 1 Enter double: 2.2 The list is: ? 2 Enter double: 3.3 The list is: ? 2 Enter double: 4.4 The list is: ? removed from list The list is:

28 ? removed from list The list is: ? removed from list The list is: 3.3 ? removed from list The list is empty ? 5 End list test All nodes destroyed All nodes destroyed

Linked Lists Types of linked lists –Singly linked list (used in example) Pointer to first node Travel in one direction (null-terminated) –Circular, singly-linked As above, but last node points to first –Doubly-linked list Each node has a forward and backwards pointer Travel forward or backward Last node null-terminated –Circular, double-linked As above, but first and last node joined

Stacks Stack –Nodes can be added/removed from top Constrained version of linked list Like a stack of plates –Last-in, first-out (LIFO) data structure –Bottom of stack has null link Stack operations –Push: add node to top –Pop: remove node from top Stores value in reference variable

Stacks Stack applications –Function calls: know how to return to caller Return address pushed on stack Most recent function call on top If function A calls B which calls C: –Used to store automatic variables Popped of stack when no longer needed –Used by compilers Example in the exercises in book

Stacks Upcoming program –Create stack from list insertAtFront, removeFromFront –Software reusability Inheritance –Stack inherits from List Composition –Stack contains a private List object –Performs operations on that object –Makes stack implementation simple

33 1 // Fig : stack.h 3 #ifndef STACK_H 4 #define STACK_H 6 #include "list.h" 8 template 9 class Stack : private List { 11 public: 13 void push( const STACKTYPE &data ) { 15 insertAtFront( data ); 17 } 20 bool pop( STACKTYPE &data ) { 22 return removeFromFront( data ); 24 } 27 bool isStackEmpty() const { 29 return isEmpty(); 31 } 34 void printStack() const { 36 print(); 38 } 40 }; 42 #endif Class Stack - ListNode *firstPtr; - ListNode *lastPtr; STACKTYPE firstPtrlastPtr +void insertAtFront( const NODETYPE & ); +void insertAtBack( const NODETYPE & ); +bool removeFromFront( NODETYPE & ); +bool removeFromBack( NODETYPE & ); +bool isEmpty() const; +void print() const;

34 1 // Fig : fig17_11.cpp 3 #include 7 #include "stack.h" // Stack class definition 9 int main(){ 11 Stack intStack; // create Stack of ints 13 cout << "processing an integer Stack" << endl; 16 for ( int i = 0; i < 4; i++ ) { 17 intStack.push( i ); 18 intStack.printStack(); 20 } 23 int popInteger; 25 while ( !intStack.isStackEmpty() ) { 26 intStack.pop( popInteger ); 27 cout << popInteger << " popped from stack" << endl; 28 intStack.printStack(); 30 } 32 Stack doubleStack; 33 double value = 1.1; 35 cout << "processing a double Stack" << endl; 38 for ( int j = 0; j< 4; j++ ) { 39 doubleStack.push( value ); 40 doubleStack.printStack(); 41 value += 1.1; 43 }

35 46 double popDouble; 48 while ( !doubleStack.isStackEmpty() ) { 49 doubleStack.pop( popDouble ); 50 cout << popDouble << " popped from stack" << endl; 51 doubleStack.printStack(); 53 } 55 return 0; 57 }

36 processing an integer Stack The list is: 0 The list is: 1 0 The list is: The list is: popped from stack The list is: popped from stack The list is: popped from stack The list is: 0 0 popped from stack The list is empty processing a double Stack The list is: 1.1 The list is: The list is:

37 The list is: popped from stack The list is: popped from stack The list is: popped from stack The list is: popped from stack The list is empty All nodes destroyed All nodes destroyed

38 1 // Fig : stackcomposition.h 3 #ifndef STACKCOMPOSITION 4 #define STACKCOMPOSITION 6 #include "list.h" 8 template 9 class Stack { 11 public: 15 void push( const STACKTYPE &data ) { 17 stackList.insertAtFront( data ); 19 } 22 bool pop( STACKTYPE &data ) { 24 return stackList.removeFromFront( data ); 26 } 29 bool isStackEmpty() const { 31 return stackList.isEmpty(); 33 } 36 void printStack() const { 38 stackList.print(); 40 } 42 private: 43 List stackList; 45 }; 47 #endif Class Stack - List stackList; STACKTYPE

Queues Queue –Like waiting in line –Nodes added to back (tail), removed from front (head) –First-in, first-out (FIFO) data structure –Insert/remove called enqueue/dequeue Applications –Print spooling Documents wait in queue until printer available –Packets on network –File requests from server

Queues Upcoming program –Queue implementation –Reuse List as before insertAtBack ( enqueue ) removeFromFront ( dequeue )

41 1 // Fig : queue.h 3 #ifndef QUEUE_H 4 #define QUEUE_H 6 #include "list.h" 8 template 9 class Queue : private List { 11 public: 13 void enqueue( const QUEUETYPE &data ) { 15 insertAtBack( data ); 17 } 20 bool dequeue( QUEUETYPE &data ) { 22 return removeFromFront( data ); 24 } 27 bool isQueueEmpty() const { 29 return isEmpty(); 31 } 34 void printQueue() const { 36 print(); 38 } 40 }; 42 #endif Class Queue - ListNode *firstPtr; - ListNode *lastPtr; QUEUETYPE firstPtrlastPtr +void insertAtFront( const NODETYPE & ); +void insertAtBack( const NODETYPE & ); +bool removeFromFront( NODETYPE & ); +bool removeFromBack( NODETYPE & ); +bool isEmpty() const; +void print() const;

42 1 // Fig : fig17_14.cpp 9 int main() { 11 Queue intQueue; 16 for ( int i = 0; i < 4; i++ ) { 17 intQueue.enqueue( i ); 18 intQueue.printQueue(); 20 } 23 int dequeueInteger; 25 while ( !intQueue.isQueueEmpty() ) { 26 intQueue.dequeue( dequeueInteger ); 27 cout << dequeueInteger << " dequeued" << endl; 28 intQueue.printQueue(); 30 } 32 Queue doubleQueue; 33 double value = 1.1; 38 for ( int j = 0; j< 4; j++ ) { 39 doubleQueue.enqueue( value ); 40 doubleQueue.printQueue(); 41 value += 1.1; } 46 double dequeueDouble; 48 while ( !doubleQueue.isQueueEmpty() ) { 49 doubleQueue.dequeue( dequeueDouble ); 50 cout << dequeueDouble << " dequeued" << endl; 51 doubleQueue.printQueue(); 52 } 57 }

43 processing an integer Queue The list is: 0 The list is: 0 1 The list is: The list is: dequeued The list is: dequeued The list is: dequeued The list is: 3 3 dequeued The list is empty processing a double Queue The list is: 1.1 The list is:

44 The list is: The list is: dequeued The list is: dequeued The list is: dequeued The list is: dequeued The list is empty All nodes destroyed All nodes destroyed

Trees Linear data structures –Lists, queues, stacks Trees –Nonlinear, two-dimensional –Tree nodes have 2 or more links –Binary trees have exactly 2 links/node None, both, or one link can be null

Trees Terminology –Root node: first node on tree –Link refers to child of node Left child is root of left subtree Right child is root of right subtree –Leaf node: node with no children –Trees drawn from root downwards B A D C

Trees Binary search tree –Values in left subtree less than parent node –Values in right subtree greater than parent Does not allow duplicate values (good way to remove them) –Fast searches, log 2 n comparisons for a balanced tree

Trees Inserting nodes –Use recursive function –Begin at root –If current node empty, insert new node here (base case) –Otherwise, If value > node, insert into right subtree If value < node, insert into left subtree If neither > nor <, must be = –Ignore duplicate

Trees Tree traversals –In-order (print tree values from least to greatest) Traverse left subtree (call function again) Print node Traverse right subtree –Preorder Print node Traverse left subtree Traverse right subtree –Postorder Traverse left subtree Traverse rigth subtree Print node

Trees Upcoming program –Create 2 template classes –TreeNode data leftPtr rightPtr –Tree rootPtr Functions –InsertNode –inOrderTraversal –preOrderTraversal –postOrderTraversal

51 1 // Fig : treenode.h 3 #ifndef TREENODE_H 4 #define TREENODE_H 7 template class Tree; 9 template 10 class TreeNode { 11 friend class Tree ; 13 public: 16 TreeNode( const NODETYPE &d ) 17 : leftPtr( 0 ), data( d ), rightPtr( 0 ) { 23 } 26 NODETYPE getData() const { 28 return data; 30 } 32 private: 33 TreeNode *leftPtr; 34 NODETYPE data; 35 TreeNode *rightPtr; 37 }; 39 #endif Class TreeNode - TreeNode *leftPtr; - NODETYPE data; - TreeNode *rightPtr; NODETYPE TreeNode

52 1 // Fig : tree.h 3 #ifndef TREE_H 4 #define TREE_H 10 #include 11 #include "treenode.h" 13 template 14 class Tree { 16 public: 17 Tree(); 18 void insertNode( const NODETYPE & ); 19 void preOrderTraversal() const; 20 void inOrderTraversal() const; 21 void postOrderTraversal() const; 23 private: 24 TreeNode *rootPtr; 27 void insertNodeHelper( 28 TreeNode **, const NODETYPE & ); 29 void preOrderHelper( TreeNode * ) const; 30 void inOrderHelper( TreeNode * ) const; 31 void postOrderHelper( TreeNode * ) const; 33 }; 36 template 37 Tree ::Tree() { 39 rootPtr = 0; 41 } Class Tree - TreeNode *rootPtr; ; NODETYPE + void insertNode( const NODETYPE & ); + void preOrderTraversal() const; + void inOrderTraversal() const; + void postOrderTraversal() const; rootNode

53 44 template 45 void Tree ::insertNode( const NODETYPE &value ) { 47 insertNodeHelper( &rootPtr, value ); 49 } 53 template 54 void Tree ::insertNodeHelper( 55 TreeNode **ptr, const NODETYPE &value ){ 58 if ( *ptr == 0 ) 59 *ptr = new TreeNode ( value ); 61 else // subtree is not empty 64 if ( value data ) 65 insertNodeHelper( &( ( *ptr )->leftPtr ), value ); 67 else 70 if ( value > ( *ptr )->data ) 71 insertNodeHelper( &( ( *ptr )->rightPtr ), value ); 73 else 74 cout << value << " dup" << endl; 76 } 79 template 80 void Tree ::preOrderTraversal() const { 82 preOrderHelper( rootPtr ); 84 } Recursive function to insert a new node. If the current node is empty, insert the new node here. If new value greater than current node ( ptr ), insert into right subtree. If less, insert into left subtree. If neither case applies, node is a duplicate -- ignore.

54 87 template 88 void Tree ::preOrderHelper( 89 TreeNode *ptr ) const { 91 if ( ptr != 0 ) { 92 cout data << ' '; // process node 93 preOrderHelper( ptr->leftPtr ); // go to left subtree 94 preOrderHelper( ptr->rightPtr ); // go to right subtree 96 } 98 } 101 template 102 void Tree ::inOrderTraversal() const { 104 inOrderHelper( rootPtr ); 106 } 109 template 110 void Tree ::inOrderHelper( 111 TreeNode *ptr ) const { 113 if ( ptr != 0 ) { 114 inOrderHelper( ptr->leftPtr ); // go to left subtree 115 cout data << ' '; // process node 116 inOrderHelper( ptr->rightPtr ); // go to right subtree 118 } 120 } Preorder: print, left, rightIn order: left, print, right

template 124 void Tree ::postOrderTraversal() const { 126 postOrderHelper( rootPtr ); 128 } 131 template 132 void Tree ::postOrderHelper( 133 TreeNode *ptr ) const { 135 if ( ptr != 0 ) { 136 postOrderHelper( ptr->leftPtr ); // go to left subtree 137 postOrderHelper( ptr->rightPtr ); // go to right subtree 138 cout data << ' '; // process node 140 } 142 } 144 #endif Postorder: left, right, print

56 1 // Fig : fig17_19.cpp 12 #include "tree.h" 14 int main() { 16 Tree intTree; 17 int intValue; 19 cout << "Enter 10 integer values:\n"; 21 for( int i = 0; i < 10; i++ ) { 22 cin >> intValue; 23 intTree.insertNode( intValue ); 25 } 27 cout << "\nPreorder traversal\n"; 28 intTree.preOrderTraversal(); 30 cout << "\nInorder traversal\n"; 31 intTree.inOrderTraversal(); 33 cout << "\nPostorder traversal\n"; 34 intTree.postOrderTraversal(); 36 Tree doubleTree; 37 double doubleValue; 39 cout << fixed << setprecision( 1 ) 40 << "\n\n\nEnter 10 double values:\n"; 42 for ( int j = 0; j < 10; j++ ) { 43 cin >> doubleValue; 44 doubleTree.insertNode( doubleValue ); 46 } 48 cout << "\nPreorder traversal\n"; 49 doubleTree.preOrderTraversal();

57 51 cout << "\nInorder traversal\n"; 52 doubleTree.inOrderTraversal(); 54 cout << "\nPostorder traversal\n"; 55 doubleTree.postOrderTraversal(); 57 cout << endl; 59 return 0; 61 } Enter 10 integer values: Preorder traversal Inorder traversal Postorder traversal Enter 10 double values: Preorder traversal Inorder traversal Postorder traversal

58 Summary User-defined class in textbook C++ Standard Template library (STL) class Header file 8.10StringCh 15string 8.8Arrayvalarray Complexcomplex 17.4List21.2.2list 17.5Stack21.4.1stack 17.6Queue21.4.2queue 17.7Tree iostream