Data Str & Algorithm HW Solutions 33

Data Str & Algorithm HW Solutions 33 - 5.4 (a)...

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

View Full Document Right Arrow Icon
33 5.3 Base Case : For the tree of one leaf node, I =0 , E =0 , n =0 ,sothe theorem holds. Induction Hypothesis : The theorem holds for the full binary tree containing n internal nodes. Induction Step : Take an arbitrary tree (call it T )of n internal nodes. Select some internal node x from T that has two leaves, and remove those two leaves. Call the resulting tree T’ . Tree T’ is full and has n 1 internal nodes, so by the Induction Hypothesis E = I +2( n 1) . Call the depth of node x as d . Restore the two children of x , each at level d +1 .Wehavenowadded d to I since x is now once again an internal node. We have now added 2( d +1) d = d +2 to E since we added the two leaf nodes, but lost the contribution of x to E . Thus, if before the addition we had E = I +2( n 1) (by the induction hypothesis), then after the addition we have E + d = I + d +2+2( n 1) or E = I +2 n which is correct. Thus, by the principle of mathematical induction, the theorem is correct.
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 5.4 (a) template <class Elem> void inorder(BinNode<Elem>* subroot) { if (subroot == NULL) return; // Empty, do nothing preorder(subroot->left()); visit(subroot); // Perform desired action preorder(subroot->right()); } (b) template <class Elem> void postorder(BinNode<Elem>* subroot) { if (subroot == NULL) return; // Empty, do nothing preorder(subroot->left()); preorder(subroot->right()); visit(subroot); // Perform desired action } 5.5 The key is to search both subtrees, as necessary. template <class Key, class Elem, class KEComp> bool search(BinNode<Elem>* subroot, Key K); if (subroot == NULL) return false; if (subroot->value() == K) return true; if (search(subroot->right())) return true; return search(subroot->left()); }...
View Full Document

Ask a homework question - tutors are online