Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 25 – Data Structures

Similar presentations


Presentation on theme: "Chapter 25 – Data Structures"— Presentation transcript:

1 Chapter 25 – Data Structures
Outline Introduction Simple-Type structs, Boxing and Unboxing Self-Referential Classes Linked Lists Stacks Queues Trees Binary Search Tree of Integer Values Binary Search Tree of IComparable Objects Many slides modified by Prof. L. Lilien (even many without an explicit message). Slides added by L.Lilien are © 2006 Leszek T. Lilien. Permision to use for non-commercial purposes slides added by L.Lilien’s will be gladly granted upon a written (e.g., ed) request.

2 Dynamic data structures
25.1 Introduction Dynamic data structures Grow and shrink at execution time Linked Lists: “Lined up in a row” Insertions and removals can occur anywhere in the list Stacks: Insertions and removals only at top Push and pop Queues: Insertions made at back, removals from front Trees, including binary trees: Facilitate high-speed searching and sorting of data Efficient elimination of duplicate items

3 25.2 Simple-Type structs, Boxing and Unboxing
Data structures can store: Simple-type values Reference-type values There are mechanisms that enable manipulation of simple-type values as objects Discussed below

4 Simple-Type structs Recall: Each simple type (int, char, …) has a corresponding struct in namespace System that declares this simple type We have structs: Boolean, Byte, Sbyte, Char, Decimal, Double, Single, Int32, UInt32, Int64, UInt64, Int16, UInt16 Simple types are just aliases for these corresponding structs So a variable can be declared: EITHER using the keyword for that simple type OR the struct name E.g., int (keyword) and Int32 (struct name) are interchangeable Methods related to a simple type are located in the corresponding struct E.g. method Parse –converting string to int value– is located in struct In32

5 Boxing Conversions All simple-type structs inherit from class ValueType in namespace System In turn, class ValueType inherits from class object => Any simple-type value can be assigned to an object variable Such an assignment is named a Boxing conversions In Boxing conversion simple-type value is copied into an object => after Boxing conversion , a simple-type value can be manipulated as an object

6 Boxing Conversions Boxing conversions can be explicit or implicit
int i = 5; // create an int value object obj1 = ( object) i; // explicitly box the int value object obj2 = i; // implicitly box the int value Now obj1 and obj2 refer to 2 different objects! Both objects include a copy of the integer value from the int variable i

7 Unboxing Conversions Unboxing conversions — used for explicit conversion of an object reference to a simple value int int1 = ( int ) obj1; // explicitly unbox the int value // that was boxed within obj1 Attempts to unbox an object reference that does not refer to a correct simple value causes InvalidCastException We’ll see later(Ch. 27) how so called “generics” eliminate the overhead of boxing/unboxing

8 25.3 Self-Referential Classes
Contains a reference member to an object of the same class type E.g.: class Node { private int data; private Node next; // self-reference to node } Reference can be used to link objects of the same type together Dynamic data structures require dynamic memory allocation Ability to obtain memory when needed Release memory when not needed any more Uses new operator Ex: Node nodeToAdd = new Node(10); Slide modified by L. Lilien

9 25.3 Self-Referential Class
1 class Node 2 { private int data; private Node next; // self-reference 5 public Node( int d ) { /* constructor body */ } 10 public int Data { get { /* get body */ } 17 set { /* set body */ } } 23 public Node Next { get { /* get body */ } 30 set { /* set body */ } } 36 } 25.3 Self-Referential Class Reference to object of same type Fig Sample self-referential Node class definition (part 1) Slide merged with next by L. Lilien

10 25.3 Self-Referential Class
data next data next 15 10 Fig Two self-referential class objects (nodes) linked together. Slide modified by L. Lilien

11 25.4 Linked Lists Linked List:
Linear collection of self-referential nodes connected by links Nodes: class objects of linked-lists Programs access linked lists through a reference to first node Subsequent nodes accessed by link-reference members Last node’s link set to null to indicate end of list Nodes can hold data of any type Nodes created dynamically reference to first node lastNode (with null link) firstNode H e …… o Slide modified by L. Lilien

12 25.4 Linked Lists H D …… Q firstNode reference lastNode refernce
Fig A graphical representation of a linked list (with an optional reference to the last node). Slide modified by L. Lilien

13 Linked lists - similar to arrays However:
Arrays are a fixed size Linked lists have no limit to size More nodes can be added as program executes Slide modified by L. Lilien

14 25.4 Linked Lists - InsertAtFront
11 7 12 new ListNode (a) firstNode 12 new ListNode 11 7 firstNode (b) Changed links Unchanged links Fig A graphical representation of the InsertAtFront operation. Slide modified by L. Lilien

15 25.4 Linked Lists - InsertAtBack
7 12 11 firtNode lastNode New ListNode 5 (b) 7 11 firstNode New ListNode 12 5 lastNode Changed links Unchanged links Fig A graphical representation of the InsertAtBack operation. Slide modified by L. Lilien

16 25.4 Linked Lists - RemoveFromFront
(a) 7 12 lastNode 11 5 firstNode 7 11 firstNode lastNode (b) 12 5 removeItem Changed links Unchanged links Fig A graphical representation of the RemoveFromFront operation. Slide modified by L. Lilien

17 25.4 Linked Lists - RemoveFromBack
7 12 lastNode 11 5 firstNode 7 11 firstNode lastNode (b) 12 5 removeItem Changed links Unchanged links Fig A graphical representation of the RemoveFromBack operation. Slide modified by L. Lilien

18 Reference to next ListNode in linked list
1 // Fig. 23.4: LinkedListLibrary.cs 2 // Class ListNode and class List definitions. 3 4 using System; 5 6 namespace LinkedListLibrary // create library 7 { // class to represent one node in a list class ListNode { private object data; // any object can be within a list node private ListNode next; // self-referential member variable 13 // constructor to create ListNode that refers to dataValue // and is last node in list (added to the end of the list) public ListNode( object dataValue ) : this( dataValue, null ) // calls constructor below { } 20 // constructor to create ListNode that refers to dataValue // and refers to next ListNode in List (added to any list // position other than the last one) public ListNode( object dataValue, ListNode nextNode ) { data = dataValue; next = nextNode; } 28 // property Next public ListNode Next { get { return next; } LinkedListLibrary.cs Reference to next ListNode in linked list Constructor for first item in list Invoke normal constructor, which will set data to dataValue and next to null Constructor to set data and next values to parameter values Accessor method so a List can access next member variable

19 Accessor method so a List can access data member variable
36 set { next = value; } } 42 // property Data public object Data { get { return data; } } 51 } // end class ListNode 53 // class List definition public class List { private ListNode firstNode; private ListNode lastNode; private string name; // string like "list" to display 60 // construct empty List with specified name public List( string listName ) { name = listName; firstNode = lastNode = null; } 67 LinkedListLibrary.cs Accessor method so a List can access data member variable Reference to first node in list Reference to last node in list Set reference to first and last nodes to null

20 Method to insert an object at the front of the list
// construct empty List with "list" as its name public List() : this( "list" ) // uses previous constructor { } 72 // Insert object at front of List. If List is empty, // firstNode and lastNode will refer to same object. // Otherwise, firstNode refers to new node. public void InsertAtFront( object insertItem ) { lock ( this ) // ignore-needed in multithreaded environment { if ( IsEmpty() ) // defined in Line 163 below firstNode = lastNode = new ListNode( insertItem ); else firstNode = new ListNode( insertItem, firstNode ); } } 88 // Insert object at end of List. If List is empty, // firstNode and lastNode will refer to same object. // Otherwise, lastNode's Next property refers to new node. public void InsertAtBack( object insertItem ) { lock ( this ) // ignore-needed in multithreaded environment { if ( IsEmpty() ) // defined in Line 163 below firstNode = lastNode = new ListNode( insertItem ); 99 LinkedListLibrary.cs Method to insert an object at the front of the list Get list lock Test if list is empty If list is empty, create new node and set firstNode and lastNode to refer to it If list is not empty, insert object by setting its next reference to the first node Method to insert object into back of list Get list lock Test if list is empty If list is empty create a new node and set firstNode and lastNode to reference it

21 Method to remove an object from the front of list
else lastNode = lastNode.Next = new ListNode( insertItem ); } } 105 // remove first node from List public object RemoveFromFront() { lock ( this ) // ignore-needed in multithreaded environ. { object removeItem = null; 112 if ( IsEmpty() ) // defined in Line 163 below throw new EmptyListException( name ); 115 removeItem = firstNode.Data; // retrieve data 117 // reset firstNode and lastNode references if ( firstNode == lastNode ) firstNode = lastNode = null; 121 else firstNode = firstNode.Next; 124 return removeItem; // return removed data } } 128 // remove last node from List public object RemoveFromBack() { lock ( this ) // ignore-needed in multithreaded environ. { object removeItem = null; If list is not empty, create a new node and set the last node’s next reference to the new node LinkedListLibrary.cs Method to remove an object from the front of list Get lock Throw exception if list is empy Set removeItem equal to data in first node If there is only one node in the list, set firstNode and lastNode references to null If there is more then one node, set firstNode to reference the second node Return data stored in node Method to remove an object from the back of the list

22 Set removeItem equal to the data in the last node
135 if ( IsEmpty() ) throw new EmptyListException( name ); 138 removeItem = lastNode.Data; // retrieve data 140 // reset firstNode and lastNode references if ( firstNode == lastNode ) // only one node in list firstNode = lastNode = null; 144 else { // walk the list until current precedes lastNode ListNode current = firstNode; 148 // loop while current node is not lastNode while ( current.Next != lastNode ) current = current.Next; // move to next node // current is now node next to the last // make current new lastNode lastNode = current; current.Next = null; } 157 return removeItem; // return removed data } } 161 // return true if List is empty public bool IsEmpty() { lock ( this ) // ignore-needed in multithreaded environment { return firstNode == null; // checks if firstNode == null } } LinkedListLibrary.cs Set removeItem equal to the data in the last node If there is only one node, set firstNode and lastNode to refer to null Loop until next to last node is reached Set lastNode to refer to the next to last node Set reference of new last node to null Return data of old last node Method to test if list is empty

23 Method to output the list LinkedListLibrary.cs
170 // output List contents virtual public void Print() { lock ( this ) // ignore-needed in multithreaded environ. { if ( IsEmpty() ) // defined in Line 163 above { Console.WriteLine( "Empty " + name ); return; } 181 Console.Write( "The " + name + " is: " ); 183 ListNode current = firstNode; 185 // output current node data while not at end of list while ( current != null ) { Console.Write( current.Data + " " ); current = current.Next; } 192 Console.WriteLine( "\n" ); } } 196 } // end class List 198 Method to output the list LinkedListLibrary.cs Tell user if list is empty Output data in list

24 Handles illegal operations on an empty list LinkedListLibrary.cs
// class EmptyListException definition public class EmptyListException : ApplicationException { public EmptyListException( string name ) : base( "The " + name + " is empty" ) { } 206 } // end class EmptyListException 208 209 } // end namespace LinkedListLibrary Handles illegal operations on an empty list LinkedListLibrary.cs

25 Create data to put in list
1 // Fig 23.5: ListTest.cs 2 // Testing class List. 3 4 using System; 5 using LinkedListLibrary; // library we created 6 7 namespace ListTest 8 { // class to test List class functionality class ListTest { static void Main( string[] args ) { List list = new List(); // create List container 15 // create data to store in List bool aBoolean = true; char aCharacter = '$'; int anInteger = ; string aString = "hello"; 21 // use List insert methods list.InsertAtFront( aBoolean ); list.Print(); list.InsertAtFront( aCharacter ); list.Print(); list.InsertAtBack( anInteger ); list.Print(); list.InsertAtBack( aString ); list.Print(); 31 // use List remove methods object removedObject; 34 ListTest.cs Create list of objects Create data to put in list Insert objects at beginning of listinto list using InsertAtFront method Insert objects at end of listinto list using InsertAtBack method Print the list

26 Remove objects from front of list using method RemoveFromFront
// remove data from list and print after each removal try { removedObject = list.RemoveFromFront(); Console.WriteLine( removedObject + " removed" ); list.Print(); 41 removedObject = list.RemoveFromFront(); Console.WriteLine( removedObject + " removed" ); list.Print(); 45 removedObject = list.RemoveFromBack(); Console.WriteLine( removedObject + " removed" ); list.Print(); 49 removedObject = list.RemoveFromBack(); Console.WriteLine( removedObject + " removed" ); list.Print(); } 54 // process exception if list empty when attempt is // made to remove item catch ( EmptyListException emptyListException ) { Console.Error.WriteLine( "\n" + emptyListException ); } 61 } // end method Main 63 } // end class ListTest 65 } ListTest.cs Remove objects from front of list using method RemoveFromFront Print the list after each remove Remove objects from back of list using method RemoveFromBack If remove is called on an empty list tell user

27 ListTest.cs Program Output
The list is: True The list is: $ True The list is: $ True 34567 The list is: $ True hello $ removed The list is: True hello True removed The list is: hello hello removed The list is: 34567 34567 removed Empty list ListTest.cs Program Output

28 Fig. 23.6 A graphical representation of the InsertAtFront operation.
We have already seen this and next 3 slides - Review yourself if needed Linked Lists - InsertAtFront 11 7 12 new ListNode (a) firstNode 12 new ListNode 11 7 firstNode (b) Changed links Unchanged links Fig A graphical representation of the InsertAtFront operation. Slide modified by L. Lilien

29 25.4 Linked Lists - InsertAtBack
7 12 11 firtNode lastNode New ListNode 5 (b) 7 11 firstNode New ListNode 12 5 lastNode Changed links Unchanged links Fig A graphical representation of the InsertAtBack operation. Slide modified by L. Lilien

30 25.4 Linked Lists - RemoveFromFront
(a) 7 12 lastNode 11 5 firstNode 7 11 firstNode lastNode (b) 12 5 removeItem Changed links Unchanged links Fig A graphical representation of the RemoveFromFront operation. Slide modified by L. Lilien

31 25.4 Linked Lists - RemoveFromBack
7 12 lastNode 11 5 firstNode 7 11 firstNode lastNode (b) 12 5 removeItem Changed links Unchanged links Fig A graphical representation of the RemoveFromBack operation. Slide modified by L. Lilien

32 Stack – a special version of a linked list:
25.5 Stacks Stack – a special version of a linked list: Last-in, first-out (LIFO) data structure: Takes and releases new nodes only at top Operations: Push: adds new entry (node) to top of stack Pop: removes top entry (node) from stack Can be used for: Storing return addresses Storing local variables

33 StackInheritance class is derived from List class
1 // Fig : StackInheritanceLibrary.cs 2 // Implementing a stack by inheriting from class List. 3 4 using System; 5 using LinkedListLibrary; 6 7 namespace StackInheritanceLibrary 8 { // class StackInheritance inherits class List's capabilities public class StackInheritance : List { // pass name "stack" to List constructor public StackInheritance() : base( "stack" ) { } 16 // place dataValue at top of stack by inserting // dataValue at front of linked list public void Push( object dataValue ) { InsertAtFront( dataValue ); } 23 // remove item from top of stack by removing // item at front of linked list public object Pop() { return RemoveFromFront(); } 30 } // end class StackInheritance 32 } StackInheritanceLibrary.cs StackInheritance class is derived from List class Call InsertAtFront method of List class to push objects Call RemoveFromFront method of List class to pop objects

34 Create objects to store in stack
1 // Fig : StackInheritanceTest.cs 2 // Testing class StackInheritance. 3 4 using System; 5 using StackInheritanceLibrary; 6 using LinkedListLibrary; 7 8 namespace StackInheritanceTest 9 { // demonstrate functionality of class StackInheritance class StackInheritanceTest { static void Main( string[] args ) { StackInheritance stack = new StackInheritance(); 16 // create objects to store in the stack bool aBoolean = true; char aCharacter = '$'; int anInteger = 34567; string aString = "hello"; 22 // use method Push to add items to stack stack.Push( aBoolean ); stack.Print(); stack.Push( aCharacter ); stack.Print(); stack.Push( anInteger ); stack.Print(); stack.Push( aString ); stack.Print(); 32 // use method Pop to remove items from stack object removedObject = null; 35 StackInheritanceTest.cs Create stack Create objects to store in stack Push objects onto the stack Print stack after each push

35 Remove objects from stack
// remove items from stack try { while ( true ) { removedObject = stack.Pop(); Console.WriteLine( removedObject + " popped" ); stack.Print(); } } 46 // if exception occurs, print stack trace catch ( EmptyListException emptyListException ) { Console.Error.WriteLine( emptyListException.StackTrace ); } 53 } // end method Main 55 } // end class StackInheritanceTest 57 } StackInheritanceTest.cs Remove objects from stack Empty stack exception

36 StackInheritanceTest.cs Program Output
The stack is: True The stack is: $ True The stack is: $ True The stack is: hello $ True hello popped 34567 popped $ popped True popped Empty stack at LinkedListLibrary.List.RemoveFromFront() in z:\ch24\linkedlistlibrary\linkedlistlibrary.cs:line 114 at StackInheritanceLibrary.StackInheritance.Pop() in z:\ch24\stackinheritancelibrary\ stackinheritancelibrary.cs:line 28 at StackInheritanceTest.StackInheritanceTest.Main(String[] args in z:\ch24\fig24_11\stackinheritancetest.cs:line 41 StackInheritanceTest.cs Program Output Line Slide 16

37 Call method InsertAtFront to push
1 // Fig : StackCompositionLibrary.cs 2 // StackComposition definition with composed List object. // (no inheritance here!) 4 using System; 5 using LinkedListLibrary; 6 7 namespace StackCompositionLibrary 8 { // class StackComposition encapsulates List's capabilities public class StackComposition { private List stack; 13 // construct empty stack public StackComposition() { stack = new List( "stack" ); } 19 // add object to stack public void Push( object dataValue ) { stack.InsertAtFront( dataValue ); } 25 // remove object from stack public object Pop() { return stack.RemoveFromFront(); } 31 StackCompositionLibrary.cs Create List object Call method InsertAtFront to push Use method RemoveFromFrontto pop

38 Call is empty to see if list has nodes StackCompositionLibrary.cs
// determine whether stack is empty public bool IsEmpty() { return stack.IsEmpty(); } 37 // output stack contents public void Print() { stack.Print(); } 43 } // end class StackComposition 45 } Call is empty to see if list has nodes StackCompositionLibrary.cs Call method Print for output

39 First-in, first-out (FIFO) data structure Operations:
25.6 Queues Queue: First-in, first-out (FIFO) data structure Nodes added to tail, removed from head Operations: Enqueue: insert node at the end Dequeue: remove node from the front Many computer applications: Printer spooling Information packets on networks

40 Class QueueInheritance derives from class List
1 // Fig : QueueInheritanceLibrary.cs 2 // Implementing a queue by inheriting from class List. 3 4 using System; 5 using LinkedListLibrary; 6 7 namespace QueueInheritanceLibrary 8 { // class QueueInheritance inherits List's capabilities public class QueueInheritance : List { // pass name "queue" to List constructor public QueueInheritance() : base( "queue" ) { } 16 // place dataValue at end of queue by inserting // dataValue at end of linked list public void Enqueue( object dataValue ) { InsertAtBack( dataValue ); } 23 // remove item from front of queue by removing // item at front of linked list public object Dequeue( ) { return RemoveFromFront(); } 30 } // end of QueueInheritance 32 } QueueInheritanceLibrary.cs Class QueueInheritance derives from class List Call InsertAtBack to enqueue Call RemoveFromFront to dequeue

41 Create objects to be inserted into queue
1 // Fig : QueueTest.cs 2 // Testing class QueueInheritance. 3 4 using System; 5 using QueueInheritanceLibrary; 6 using LinkedListLibrary; 7 8 namespace QueueTest 9 { // demonstrate functionality of class QueueInheritance class QueueTest { static void Main( string[] args ) { QueueInheritance queue = new QueueInheritance(); 16 // create objects to store in the stack bool aBoolean = true; char aCharacter = '$'; int anInteger = 34567; string aString = "hello"; 22 // use method Enqueue to add items to queue queue.Enqueue( aBoolean ); queue.Print(); queue.Enqueue( aCharacter ); queue.Print(); queue.Enqueue( anInteger ); queue.Print(); queue.Enqueue( aString ); queue.Print(); 32 // use method Dequeue to remove items from queue object removedObject = null; 35 QueueTest.cs Create queue Create objects to be inserted into queue Enqueue objects Print queue after each enqueue

42 Print queue after each enqueue
// remove items from queue try { while ( true ) { removedObject = queue.Dequeue(); Console.WriteLine( removedObject + " dequeue" ); queue.Print(); } } 46 // if exception occurs, print stack trace catch ( EmptyListException emptyListException ) { Console.Error.WriteLine( emptyListException.StackTrace ); } 53 } // end method Main 55 } // end class QueueTest 57 } QueueTest.cs Dequeue objects Print queue after each enqueue

43 QueueTest.cs Program Output
The queue is: True The queue is: True $ The queue is: True $ 34567 The queue is: True $ hello True dequeue The queue is: $ hello $ dequeue The queue is: hello 34567 dequeue The queue is: hello hello dequeue Empty queue at LinkedListLibrary.List.RemoveFromFront() in z:\ch24\linkedlistlibrary\linkedlistlibrary.cs:line 114 at QueueInheritanceLibrary.QueueInheritance.Dequeue() in z:\ch24\queueinheritancelibrary\ queueinheritancelibrary.cs:line 28 at QueueTest.QueueTest.Main(String[] args) in z:\ch24\fig24_13\queuetest.cs:line 41 QueueTest.cs Program Output

44 Tree: non-linear, two-dimensional data structure Binary tree:
25.7 Trees Tree: non-linear, two-dimensional data structure Binary tree: Each node contains data & two links (hence “binary in the name): left link and right link Root node: “top” node in a tree Links refer to child nodes Leaf node: node with no children B X A Y

45 25.7 Trees Binary search tree:
Values in left subtree are less than the value of the subtree’s parent Values in right subtree are greater than the value of the subtree’s parent J A P M 47 25 77 11 65 93 43

46 25.7.1 Binary Search Tree of Integer Values
Traversal: method of retrieving data from a tree In these methods if there is a subtree, recursively the traversal is called recursively Kinds of traversals: Inorder traversal: Get data from left subtree/child of node Get data from node Get data from right subtree/child of node Example (figure) 47 25 77 11 65 93 43

47 25.7.1 Binary Search Tree of Integer Values
47 25 77 11 65 93 43 Preorder traversal: Get data from node Get data from left subtree/child of node Get data from right subtree/child of node Example: Postorder traversal Example: Level-order traversal Visit nodes of tree row by row, from left to right Example:

48 25.7 Trees Reference to the tree B A D C
Fig A graphical representation of a binary tree.

49 Fig. 23.16 A binary search tree containing 12 values.
25.7 Trees 47 25 77 11 7 17 65 93 68 43 31 44 Fig A binary search tree containing 12 values.

50 Left and right subtree references
1 // Fig : BinaryTreeLibrary.cs 2 // Definition of class TreeNode and class Tree. 3 4 using System; 5 6 namespace BinaryTreeLibrary 7 { // class TreeNode definition class TreeNode { private TreeNode leftNode; private int data; private TreeNode rightNode; 14 // initialize data and make this a leaf node public TreeNode( int nodeData ) { data = nodeData; leftNode = rightNode = null; // node has no children } 21 // LeftNode property public TreeNode LeftNode { get { return leftNode; } 29 set { leftNode = value; } } 35 BinaryTreeLibrary.cs Left and right subtree references Data stored in node Since new nodes are leaf, set subtree references to null Accessor methods for left subtree

51 Accessor methods for nodes data BinaryTreeLibrary.cs
// Data property public int Data { get { return data; } 43 set { data = value; } } 49 // RightNode property public TreeNode RightNode { get { return rightNode; } 57 set { rightNode = value; } } 63 64 Accessor methods for nodes data BinaryTreeLibrary.cs Accessor methods for right subtree

52 Method to determine location of new node
// insert TreeNode into Binary Search Tree containing nodes; // ignore duplicate values public void Insert( int insertValue ) { // insert in left subtree if ( insertValue < data ) { // insert new TreeNode if ( leftNode == null ) leftNode = new TreeNode( insertValue ); 75 // continue traversing left subtree else leftNode.Insert( insertValue ); } 80 // insert in right subtree else if ( insertValue > data ) { // insert new TreeNode if ( rightNode == null ) rightNode = new TreeNode( insertValue ); 87 // continue traversing right subtree else rightNode.Insert( insertValue ); } // ignore if insertValue == data (duplicate value) } // end method Insert 94 } // end class TreeNode 96 Method to determine location of new node BinaryTreeLibrary.cs If value of new node is less than root, and the left subtree is empty, insert node as left child of root If left subtree is not empty, recursively call Insert to determine location of new node in subtree If value of new node is greater than root, and the right subtree is empty, insert node as right child of root If right subtree is not empty, recursively call Insert to determine location of new node in subtree

53 Reference to root of tree BinaryTreeLibrary.cs
// class Tree definition public class Tree { private TreeNode root; 101 // construct an empty Tree of integers public Tree() { root = null; } 107 // Insert a new node in the binary search tree. // If the root node is null, create the root node here. // Otherwise, call the insert method of class TreeNode. public void InsertNode( int insertValue ) { lock ( this ) // ignore locks { if ( root == null ) root = new TreeNode( insertValue ); 117 else root.Insert( insertValue ); // see l.67 } } 122 // begin preorder traversal public void PreorderTraversal() { lock ( this ) { PreorderHelper( root ); } } 131 Reference to root of tree BinaryTreeLibrary.cs Set root to null when tree first created Method to insert a new node into tree If tree is empty insert new node as root If tree is not empty call Insert to determine location of new node Perform preorder traversal Call PreorderHelper to help perform traversal

54 Method to help with preorder traversal BinaryTreeLibrary.cs
// recursive method to perform preorder traversal private void PreorderHelper( TreeNode node ) { if ( node == null ) return; 137 // output data from this node Console.Write( node.Data + " " ); 140 // traverse left subtree PreorderHelper( node.LeftNode ); 143 // traverse right subtree PreorderHelper( node.RightNode ); } 147 // begin inorder traversal public void InorderTraversal() { lock ( this ) { InorderHelper( root ); } } 156 // recursive method to perform inorder traversal private void InorderHelper( TreeNode node ) { if ( node == null ) return; 162 // traverse left subtree InorderHelper( node.LeftNode ); 165 Method to help with preorder traversal BinaryTreeLibrary.cs Display node data Call PreorderHelper recursively on left subtree Call PreorderHelper recursively on right subtree Perform inorder traversal Call InorderHelper to help with traversal Method to help with inorder traversal Call InorderHelper recursively on left subtree

55 Call InorderHelper recursively on right subtree
// output node data Console.Write( node.Data + " " ); 168 // traverse right subtree InorderHelper( node.RightNode ); } 172 // begin postorder traversal public void PostorderTraversal() { lock ( this ) { PostorderHelper( root ); } } 181 // recursive method to perform postorder traversal private void PostorderHelper( TreeNode node ) { if ( node == null ) return; 187 // traverse left subtree PostorderHelper( node.LeftNode ); 190 // traverse right subtree PostorderHelper( node.RightNode ); 193 // output node data Console.Write( node.Data + " " ); } 197 } // end class Tree 199 } Display node data BinaryTreeLibrary.cs Call InorderHelper recursively on right subtree Perform postorder traversal Call PostorderHelper to help with traversal Method to help with postorder traversal Call PostorderHelper recursively on left subtree Call PostorderHelper recursively on right subtree Display node data

56 Insert ten nodes in tree
1 // Fig : TreeTest.cs 2 // This program tests class Tree. 3 4 using System; 5 using BinaryTreeLibrary; 6 7 namespace TreeTest 8 { // class TreeTest definition public class TreeTest { // test class Tree static void Main( string[] args ) { Tree tree = new Tree(); int insertValue; 17 Console.WriteLine( "Inserting values: " ); Random random = new Random(); 20 // insert 10 random integers from 0-99 in tree for ( int i = 1; i <= 10; i++ ) { insertValue = random.Next( 100 ); Console.Write( insertValue + " " ); 26 tree.InsertNode( insertValue ); } 29 // perform preorder traveral of tree Console.WriteLine( "\n\nPreorder traversal" ); tree.PreorderTraversal(); 33 TreeTest.cs Create a tree Insert ten nodes in tree Call preorder traversal

57 TreeTest.cs Program Output
// perform inorder traveral of tree Console.WriteLine( "\n\nInorder traversal" ); tree.InorderTraversal(); 37 // perform postorder traveral of tree Console.WriteLine( "\n\nPostorder traversal" ); tree.PostorderTraversal(); Console.WriteLine(); } 43 } // end class TreeTest 45 } Call inorder traversal TreeTest.cs Program Output Call postorder traversal Inserting values: Preorder traversal Inorder traversal Postorder traversal

58 25.7 Binary Search Tree of Integer Values
27 13 42 6 33 48 17 Fig A binary search tree.

59 25.7.2 Binary Search Tree of IComparable Objects
Can use polymorphism to manipulate objects of different types in uniform ways Binary search trees can be implemented to manipulate data of any object that implements the IComparable interface Implementation of IComparable defines: CompareTo method E.g.: public void Insert( IComparable insertValue ) { if ( insertValue.CompareTo( data ) < 0 ) } insertValue.CompareTo( data ) returns value: < 0 if insertValue < data = 0 if they are equal > 0 if insertValue > data

60 BinaryTreeLibrary2.cs 1 // Fig. 23.20: BinaryTreeLibrary2.cs
2 // Definition of class TreeNode and class Tree for IComparable 3 // objects. 4 5 using System; 6 7 namespace BinaryTreeLibrary2 8 { // class TreeNode definition class TreeNode { private TreeNode leftNode; private IComparable data; // polymorphic data stored in node private TreeNode rightNode; 15 // initialize data and make this a leaf node public TreeNode( IComparable nodeData ) { data = nodeData; leftNode = rightNode = null; // node has no children } 22 // LeftNode property public TreeNode LeftNode { get { return leftNode; } 30 set { leftNode = value; } } BinaryTreeLibrary2.cs

61 BinaryTreeLibrary2.cs 36 37 // Data property
public IComparable Data { get { return data; } 44 set { data = value; } } 50 // RightNode property public TreeNode RightNode { get { return rightNode; } 58 set { rightNode = value; } } 64 BinaryTreeLibrary2.cs

62 65 // insert TreeNode into Tree that contains nodes;
// ignore duplicate values public void Insert( IComparable insertValue ) { // insertValue of polymorphic-enabling type IComparable // insert in left subtree if ( insertValue.CompareTo( data ) < 0 ) // need { // ‘insertValue < data’ not sufficient – cf. sl.47 l.70) // insert new TreeNode if ( leftNode == null ) leftNode = new TreeNode( insertValue ); 75 // continue traversing left subtree else leftNode.Insert( insertValue ); // recursive } 80 // insert in right subtree else if ( insertValue.CompareTo( data ) > 0 ) {// ‘insertValue > data’ not sufficient – cf. sl.47 l.82 // insert new TreeNode if ( rightNode == null ) rightNode = new TreeNode( insertValue ); 87 // continue traversing right subtree else rightNode.Insert( insertValue ); // recursive } 92 // ignore if insertValue.CompareTo( data ) == 0 (duplicate value) } // end method Insert 94 } // end class TreeNode 96 BinaryTreeLibrary2.cs Use Icomparable’s method CompareTo to determine if new node is less than its parent Use Icomparable’s method CompareTo to determine if new node is greater than its parent

63 BinaryTreeLibrary2.cs 97 // class Tree definition
public class Tree // differences w.r.t. Fig in red { private TreeNode root; 101 // construct an empty Tree of integers public Tree() { root = null; } 107 // Insert a new node in the binary search tree. // If the root node is null, create the root node here. // Otherwise, call the insert method of class TreeNode. public void InsertNode( IComparable insertValue ) { lock ( this ) { if ( root == null ) root = new TreeNode( insertValue ); 117 else root.Insert( insertValue ); // use Insert from } // previous slide to insert new node into tree } // rooted at ‘root’ 122 // begin preorder traversal public void PreorderTraversal() { lock ( this ) { PreorderHelper( root ); } } 131 BinaryTreeLibrary2.cs

64 132 // recursive method to perform preorder traversal
private void PreorderHelper( TreeNode node ) { if ( node == null ) return; 137 // output node data Console.Write( node.Data + " " ); 140 // traverse left subtree PreorderHelper( node.LeftNode ); 143 // traverse right subtree PreorderHelper( node.RightNode ); } 147 // begin inorder traversal public void InorderTraversal() { lock ( this ) { InorderHelper( root ); } } 156 // recursive method to perform inorder traversal private void InorderHelper( TreeNode node ) { if ( node == null ) return; 162 // traverse left subtree InorderHelper( node.LeftNode ); 165 BinaryTreeLibrary2.cs

65 BinaryTreeLibrary2.cs 166 // output node data
Console.Write( node.Data + " " ); 168 // traverse right subtree InorderHelper( node.RightNode ); } 172 // begin postorder traversal public void PostorderTraversal() { lock ( this ) { PostorderHelper( root ); } } 181 // recursive method to perform postorder traversal private void PostorderHelper( TreeNode node ) { if ( node == null ) return; 187 // traverse left subtree PostorderHelper( node.LeftNode ); 190 // traverse right subtree PostorderHelper( node.RightNode ); 193 // output node data Console.Write( node.Data + " " ); } 197 } // end class Tree 199 } BinaryTreeLibrary2.cs

66 Populate trees with int, double and string values
1 // Fig : TreeTest.cs 2 // This program tests class Tree. 3 4 using System; 5 using BinaryTreeLibrary2; 6 7 namespace TreeTest 8 { // class TreeTest definition public class TreeTest { // test class Tree static void Main( string[] args ) { int[] intArray = { 8, 2, 4, 3, 1, 7, 5, 6 }; double[] doubleArray = { 8.8, 2.2, 4.4, 3.3, 1.1, 7.7, 5.5, 6.6 }; string[] stringArray = { "eight", "two", "four", "three", "one", "seven", "five", "six" }; 20 // create int Tree // - using: public public class Tree Tree intTree = new Tree(); // empty tree populateTree( intArray, intTree, "intTree" ); // next sl. traverseTree( intTree, "intTree" ); // next sl. 25 // create double Tree Tree doubleTree = new Tree(); populateTree( doubleArray, doubleTree, "doubleTree" ); traverseTree( doubleTree, "doubleTree" ); 30 // create string Tree Tree stringTree = new Tree(); populateTree( stringArray, stringTree, "stringTree" ); traverseTree( stringTree, "stringTree" ); } TreeTest.cs Populate trees with int, double and string values

67 Method to add data from arrays to trees
36 // populate Tree with array elements static void populateTree( Array array, Tree tree, string name ) { Console.WriteLine( "\nInserting into " + name + ":" ); 42 foreach ( IComparable data in array ) { Console.Write( data + " " ); tree.InsertNode( data ); } } 49 // insert perform traversals static void traverseTree( Tree tree, string treeType ) { // perform preorder traveral of tree Console.WriteLine( "\n\nPreorder traversal of " + treeType ); tree.PreorderTraversal(); 57 // perform inorder traveral of tree Console.WriteLine( "\n\nInorder traversal of " + treeType ); tree.InorderTraversal(); 62 Method to add data from arrays to trees TreeTest.cs Insert nodes into tree Method to traverse tree Perform preorder traversal Perform inorder traversal

68 TreeTest.cs Program Output
// perform postorder traveral of tree Console.WriteLine( "\n\nPostorder traversal of " + treeType ); tree.PostorderTraversal(); Console.WriteLine( "\n" ); } 69 } // end class TreeTest 71 } TreeTest.cs Program Output Perform postorder traversal Inserting into intTree: Preorder traversal of intTree Inorder traversal of intTree Postorder traversal of intTree  

69 TreeTest.cs Program Output
Inserting into doubleTree: Preorder traversal of doubleTree Inorder traversal of doubleTree Postorder traversal of doubleTree Inserting into stringTree: eight two four three one seven five six Preorder traversal of stringTree eight two four five three one seven six Inorder traversal of stringTree eight five four one seven six three two Postorder traversal of stringTree five six seven one three four two eight TreeTest.cs Program Output

70 The End


Download ppt "Chapter 25 – Data Structures"

Similar presentations


Ads by Google