CSCA58S SECOND TERM TEST, SPRING 1996 Page 5 of 6 Question 4 (c) [10 marks] The second result statement should read: result leftCount + rightCount + 1
function frequency (value : int, root : ^treeNode) : int var match : int := 0 >> the rest of the function goes here ... << end frequencyVariable `match' certainly would be initialized on every call to frequency, but remember that there is not just one variable called `match'. Every call to frequency has its own instance of this variable. (Look back at how we traced the factorial function in class.) And no call to frequency has access to the other instances of the variable. So recursive calls to frequency cannot contribute to the final answer by modifying a shared variable called `match'.
You are thinking the wrong way about how communication between instances of the function should work. When your frequency function calls itself with a smaller problem to solve (ie a smaller tree), the old and new instances of the function should not communicate via this answer variable. They should communicate exclusively through the function call itself -- the parameters and the returned value.
It will help if you think about the answer (that frequency should give back) in terms of answers to smaller instances of the problem. (Remember how we solved factorial the "lazy" way in class?) The questions on slides 328-331 try to lead you to think this way.