Data Str &amp; Algorithm HW Solutions 34

Data Str &amp; Algorithm HW Solutions 34 - 12 16 = 75(b...

This preview shows page 1. Sign up to view the full content.

34 Chap. 5 Binary Trees 5.6 The key is to use a queue to store subtrees to be processed. template <class Elem> void level(BinNode<Elem>* subroot) { AQueue<BinNode<Elem>*> Q; Q.enqueue(subroot); while(!Q.isEmpty()) { BinNode<Elem>* temp; Q.dequeue(temp); if(temp != NULL) { Print(temp); Q.enqueue(temp->left()); Q.enqueue(temp->right()); }}} 5.7 template <class Elem> int height(BinNode<Elem>* subroot) { if (subroot == NULL) return 0; // Empty subtree return 1 + max(height(subroot->left()), height(subroot->right())); } 5.8 template <class Elem> int count(BinNode<Elem>* subroot) { if (subroot == NULL) return 0; // Empty subtree if (subroot->isLeaf()) return 1; // A leaf return 1 + count(subroot->left()) + count(subroot->right()); } 5.9 (a) Since every node stores 4 bytes of data and 12 bytes of pointers, the overhead fraction is
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 12 / 16 = 75% . (b) Since every node stores 16 bytes of data and 8 bytes of pointers, the overhead fraction is 8 / 24 ≈ 33% . (c) Leaf nodes store 8 bytes of data and 4 bytes of pointers; internal nodes store 8 bytes of data and 12 bytes of pointers. Since the nodes have different sizes, the total space needed for internal nodes is not the same as for leaf nodes. Students must be careful to do the calculation cor-rectly, taking the weighting into account. The correct formula looks as follows, given that there are x internal nodes and x leaf nodes. 4 x + 12 x 12 x + 20 x = 16 / 32 = 50% . (d) Leaf nodes store 4 bytes of data; internal nodes store 4 bytes of pointers. The formula looks as follows, given that there are x internal nodes and...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online