CS146
Chris Pollett
Apr 7, 2014
ALLOCATE-OBJECT() 1 if free == NIL 2 error "out of space" 3 else 4 x = free 5 free = x.next 6 return x FREE-OBJECT(x) 1 x.next = free 2 free = x
Which of the following statements is true?
Which of the following statements is true?
Let `x` be a node in a binary search tree. If `y` is a node in the left subtree of `x`, then `y.key le x.key`. If `y` is a node in the right subtree of `x`, then `y.key ge x.key`.
INORDER-TREE-WALK(x) 1 if x != NIL 2 INORDER-TREE-WALK(x.left) 3 print x.key 4 INORDER-TREE-WALK(x.right)
Theorem. If `x` is the root of an `n`-node subtree, then the call INORDER-TREE-WALK(x) takes `Theta(n)` time.
Proof. Let `T(n)` denote the time taken by INORDER-TREE-WALK(x). Since INORDER-TREE-WALK visits all `n` nodes of the subtree, we have `T(n) = Omega(n)`. It remains to show that `T(n) = O(n)`.
On an empty tree INORDER-TREE-WALK takes a fixed constant `c gt 0` amount of time. So `T(0) = c`.
For `n gt 0`, suppose `x` has a `k`-node left subtree and a `n-k-1` node right subtree. The time to perform INORDER-TREE-WALK(x) is bounded by `T(n) le T(k) + T(n - k -1) + d` where `d gt 0` is the time to execute the body of INORDER-TREE-WALK(x) ignoring the recursive calls.
We use the substitution method to show that `T(n) = O(n)`, by proving that `T(n) le (c + d)n +c`. For `n = 0`, we have `(c + d)cdot 0 +c = c = T(0)`. For `n gt 0`, we have:
`T(n) le T(k) + T(n - k - 1) +d`
`qquad = ((c+d)k +c) + ((c+d)(n-k -1) + c) +d` by the induction hypothesis
`qquad = (c+d)n + c - (c + d) + c + d`
`qquad = (c+d)n +c`, so the induction holds, completing the proof. QED.