100 likes | 216 Views
CS 210 Revision 2 Spring 2012. BST, Hash Tables, Heaps. Write a function INTERNAL to return the number of internal nodes in a BST. template <class keyType , class dataType > int binaryTree < keyType , dataType >::INTERNAL() { NodePointer aRoot ; aRoot = root;
E N D
CS 210 Revision 2Spring 2012 BST, Hash Tables, Heaps
Write a function INTERNAL to return the number of internal nodes in a BST template <class keyType, class dataType> intbinaryTree<keyType, dataType>::INTERNAL() { NodePointeraRoot; aRoot = root; return INTERNAL2(aRoot); } template <class keyType, class dataType> intbinaryTree<keyType, dataType>::INTERNAL2(NodePointeraRoot) { if(aRoot != NULL) { if(aRoot->left != NULL || aRoot->right != NULL) return 1 + INTERNAL2(aRoot->left) + INTERNAL2(aRoot->right); return INTERNAL2(aRoot->left) + INTERNAL2(aRoot->right); } return 0; }
Write a function MINPOS returns the minimum key in a BST template <class keyType, class dataType> keyTypebinaryTree<keyType, dataType>::MINPOS () { NodePointer cur = root; while(cur != NULL) { if(cur->left == NULL) return cur->key; cur = cur->left; } }
Code a recursive procedure BACKTRAVERSE to display the keys in the nodes of a BST in descending order template <class keyType, class dataType> void binaryTree<keyType, dataType>::BACKTRAVERSE() { if(root != NULL) BACK (root); else cout << “Tree is empty” << endl; } template <class keyType, class dataType> void binaryTree<keyType, dataType>::BACK(NodePointeraRoot) { if (aRoot->right != NULL) BACK (aRoot->right); cout << aRoot->key << " " << aRoot->data << endl; if (aRoot->left != NULL) BACK (aRoot->left); }
Hash Tables Show the hash table of size 11 after insertion of the following sequence of keys using linear probing: 25 , 42 , 95 , 108 , 109 , 162 , 198 , 37 , 66 , 223 , 124 Use a hash function F( key ) = ( key mod 10 ) mod 11 What is the average search cost per key in that table?
Heaps Given the following array of keys : ( 4 , 4 , 13 , 6 , 12 , 15 , 9 ) Show the steps of building up a minimum heap for that array and the removal from the heap to sort the array.
1 1 1 1 1 1 2
4 4 2 2 1
Write a function to merge two minimum heaps into one minimum heap void Merge2Heaps(PQ<int> & Heap1, PQ<int> & Heap2, PQ<int> & Heapm, int N, int M) { int i, x1, x2; int K = (M>N)?N:M; for (i = 1; i <= K; i++) { x1 = Heap1.remove(); x2 = Heap2.remove(); if(x1 < x2) // for efficiency { Heapm.insert(x1); Heapm.insert(x2); } else { Heapm.insert(x2); Heapm.insert(x1); } } if(N>M) for( ; i<=K+abs(N-M); i++) { x1 = Heap1.remove(); Heapm.insert(x1); } else for( ; i<=K+abs(N-M); i++) { x2 = Heap2.remove(); Heapm.insert(x2); } }