CS313E: Fall 2011 -- Quiz5 Answers ---------------------------------------------------------------------- 1. (10 points) Assume you have a binary expression tree representing (5 + 8) \times (7 + 2) and that ``visiting'' a node means printing the value stored at that node: The tree will be: * / \ + + / \ / \ 5 8 7 2 a. What is printed for an inorder traversal of the tree? 5 + 8 * 7 + 2 b. For a postorder traversal? 5 8 + 7 2 + * c. For a preorder traversal? * + 5 8 + 7 2 d. For a level order traversal? * + + 5 8 7 2 e. What is the complexity of each of these traverals? They are all linear. ---------------------------------------------------------------------- 2. (5 points) Write a Boolean-valued Python function isInt( str ) that will return True if a string represents a legal integer value (including negatives). The string can have whitespace at either end (but not in the middle). For example, isInt(str) should return True if str is any of " -12", "0 " or " 156 ", but return False on " 15 6 " or "- 3". def isInt( str ): s = str.strip() return ( s.isdigit() or ( s[0] == '-' and s[1:].isdigit() )) >>> from quiz5 import * >>> isInt("-") '' >>> isInt("-2") True >>> isInt("-2A") False >>> isInt("-123 45") False ---------------------------------------------------------------------- 3. (5 points) Write an integer valued Python function countNodes( tree ), that will return the number of nodes in a BinaryTree. Remember that BinaryTree is really a ``wrapper'' around the BinaryTreeNode class, so you will probably need an auxiliary function. def countNodesAux(node): if not node: return 0 else: return 1 \ + countNodesAux( node.getLeft() ) \ + countNodesAux( node.getRight() ) def countNodes( tree ): root = tree.getRoot() if not root: return 0 else: return countNodesAux( root ) import random input = [ random.randint(0, 999) for i in range(200) ] tree = BinarySearchTree() for i in input: tree.insert(i) print("Tree contains ", countNodes( tree ), " nodes!") def countNodesAux(node): if not node: return 0 else: return 1 \ + countNodesAux( node.getLeft() ) \ + countNodesAux( node.getRight() ) def countNodes( tree ): root = tree.getRoot() if not root: return 0 else: return countNodesAux( root ) # Some code to test it: import random input = [ random.randint(0, 999) for i in range(200) ] tree = BinarySearchTree() for i in input: tree.insert(i) print("Tree contains ", countNodes( tree ), " nodes!") >>> from Trees import * Tree contains 200 nodes!