EXERCISES ON BINARY TREES READING ------- Sedgewick, 217-223, 230-241, 477-508 EXERCISES --------- 1. Write a C program to print all the keys less than a given value v in a binary search tree. 2. Draw the binary tree representation (see Property 5.4) of the tree 3. Give the inorder and postorder traversal for the tree whose preorder traversal is A B C - - D - - E - F - -. The letters correspond to labelled internal nodes; the minus signs to external nodes. 4. Sedgewick, Exercise 5.79 5. Give the stack contents, in the style of Figure 5.27, for the preorder, inorder, and postorder traversals of the center tree in Exercise 5.79. 6. Sedgewick, Exercise 12.27 7. Sedgewick, Exercise 12.33 8. Sedgewick, Exercise 12.44 9. Sedgewick, Exercise 12.49 10. A binary tree is said to be "balanced" if both of its subtrees are balanced and the height of its left subtree differs from the height of its right subtree by at most 1. Write a C program to determine whether a given binary tree is balanced. ------------------------------------ ANSWERS TO EXERCISES ON BINARY TREES 1. void smaller(link tree, int v) { if ( tree == NULL ) return; smaller(tree->l, v); if ( tree->key >= v ) return; printf("%d ", v); smaller(tree->r, v); } 2. . . . . 3. Inorder: - C - B - D - A - E - F - Postorder: - - C - - D B - - - F E A 4. left middle right preorder D B A C F E G C B A D E E D B A C H F G I inorder A B C D E F G A B C D E A B C D E F G H I postorder A C B E G F D A B E D C A B C D G F I H E level-order D B F A C E G C B D A E E D H B C F I A G 5. preorder inorder postorder C* C* C* C B* D* B* C D* B* D* C B* D* A* B C D* A* B D* C B A* D* A B C D* A B D* C A* D* B C D* B D* C A D* C D* D* C D* D* E* D C D E* D E* E D C E* E* D C E E C 6. S E A Y Q U T I O N 7. 8. 9. If the BST is built by Prog. 12.7 or 12.9, the equal keys are on the right. int searcheqR(link h, Key v) { Key t = key(h->item); if (h == z) return 0; if less(v, t) return searcheqR(h->l, v); else return searcheqR(h->r, v) + (eq(v, t) ? 1 : 0); } int STsearcheq(Key v) { return searcheqR(head, v); } 10. Apparently, the height needs to be computed, at least until some unbalanced node is found. So this routine returns the height, -1 if the tree is not balanced. int balanced(link tree) { int bl, br; if ( tree == NULL ) return 0; bl = balanced(tree->l); br = balanced(tree->r); if (bl < 0 || br < 0) return -1; if (bl == br) return bl + 1; if (bl == br + 1) return bl + 1; if (bl == br - 1) return br + 1; return -1; }