Cormen Solution
Cormen Solution
Summer 2010
Katie Fraser
CSID: kfraser
======
17.1-1
======
No. We achieved that result by observing that we can only pop as many
elements from the stack as we have pushed onto it. Since we could only push
O(n) elements in n operations, we could only pop/multipop n elements as well,
for an amortized cost of O(n/n) = O(1).
If we add the multi-push operation, then we can add or remove O(n) elements
in each successive operation, so the running time is O(n^2) for n operations.
The amortized cost would be O(n^2/n) = O(n).
======
17.1-2
======
Suppose we add a DECREMENT operation to the k-bit counter. With k bits,
the INCREMENT operation is THETA(k) in the worst case (flip all ones to
zeroes). With DECREMENT, the worst case is also THETA(k) (flip all zeroes
to ones).
So given a sequence of n operations consisting of alternating INCREMENT
and DECREMENT operations, the time would be THETA(nk).
======
12.1-3
======
Non-recursive algorithm for inorder tree walk:
ITERATIVE-INORDER-WALK(x)
check=true;
Stack s;
push(s,x);
while( s is not empty ) {
while(left[x]!=NIL) { //if there are left-children, put them
push(s,left[x]);//on the stack
x=left[x];
}
while(check==true){
//always true the first time
x=pop(s);
//pop and print top element
print(x);
if(right[x]!=NIL )
//if there is a right-child,
push(s,right[x]); //put on stack and start over
x=right[x];
check=false;
}
//otherwise keep popping the stack
check=true;
//set check back to true
}
======
12.1-4
======
12
/ \
2 6
10 14
/\ /\
/\
/\
1 3 5 7 9 11 13 15
/\ /\ /\ /\ /\ /\ /\ /\
NN NN NN NN NN NN NN NN
/ \