Homework Assignment VIII Solution

1 The following array of current size 11 represents a heap structure:

123456789101112
9776614254593123174449 
The tree diagram of this heap is shown below:



a. (5 points) Insert a new value 86 into the heap. Draw the new heap when done. [Increase the heap size from 11 to 12, place 86 initially into slot 12 of the array, then perform upheap to restore the heap conditions.]

123456789101112
977661425459312317444986
977686425461312317444959

b. (10 points) Start again with the original heap of 11 elements. Show the result of each pass of HEAPSORT. Note: After one pass 97 is in position 11 and the values in positions 1 .. 10 again form a heap.
1234567891011
9776614254593123174449
7654614249593123174497
6154594249443123177697
5954444249173123617697
5449444223173159617697
4942443123175459617697
4442173123495459617697
4231172344495459617697
3123174244495459617697
2317314244495459617697
1723314244495459617697

2. (5 points) Write a C++ function that takes as input a pointer to the root of a binary tree, and prints the node values of the tree in level order. Assume you have available a Queue Class, to build a queue of node pointers, with the following public member functions:

	// default constructor (makes the empty queue)
	Queue ();
	
	// destructor
	~Queue();
	
	// conditionals: empty? full? - DonŐt worry about full.
	bool IsEmpty ();
	
	// add new item to the queue
	Queue& Enqueue (Node* data);
	
	// remove item from the queue
	Node* Dequeue ();
	};

void levelOrder(Node* t){ Queue Q; if (t) Q.Enqueue(t); while (!Q.IsEmpty()){ Node* p = Q.Dequeue(); cout << P->data << endl; if (p->left) Q.Enqueue(p-left); if (p->right) Q.Enqueue(p->right); } }

3. (5 points)Write a recursive function

	int PrintRange(Node* root, int low, int high);
that given a Binary Search Tree and low and high values, prints all records (data values) that fall between the two values. For full credit, the function PrintRange should visit as few nodes as possible.
int PrintRange(Node* root, int low, int high){
	// This will print the records in order
	if (root){
		datatype d = root->data;
		if ((low < d) && (root->left)) PrintRange(root->left, low, high);
		if ((low <= d) && (d <= high)) cout << root->data << endl;
		if ((d < high) && (root->right)) PrintRange(root->right, low, high);
	}
}


Last Updated: May 26, 1997 9:38 pm by

Harriet Fell
College of Computer Science, Northeastern University
360 Huntington Avenue #161CN,
Boston, MA 02115
Internet: fell@ccs.neu.edu
Phone: (617) 373-2198 / Fax: (617) 373-5121
The URL for this document is: http://www.ccs.neu.edu/home/fell/COM1101/HW/HW8/hw8Solution.html