RecurrenceRelationHandout.docx

advertisement
Name: ___________________________________________ Netid: _____________________
private boolean containsNodeBST(int value, MikesIntTreeNode current) {
if(current == null) return false;
if(current.value == value) return true;
if(value < current.value) {
return containsNode(value, current.left);
} else {
return containsNode(value, current.right);
}
}
Write the recurrence relation, assuming the tree is height balanced.
Solve the recurrence relation.
Write the recurrence relation, not assuming the tree is height balanced.
Solve the recurrence relation.
private int computeHeight(MikesIntTreeNode current) {
if(current == null)
return 0;
int lResult = computeHeight(current.left);
int rResult = computeHeight(current.right);
if(lResult > rResult) {
return lResult + 1;
} else {
return rResult + 1;
}
}
Write the recurrence relation, assuming the tree is super-not height balanced (that is one long chain).
private boolean isHeightBalanced(MikesIntTreeNode current) {
int heightLeft = computeHeight(current.left);
int heightRight = computeHeight(current.right);
if (Math.abs(heightLeft - heightRight) >= 2) {
return false;
}
return isHeightBalanced(current.left) &&
isHeightBalanced(current.right);
}
Write the recurrence relation, assuming the tree is height balanced.
Solve the recurrence relation.
The public method max returns the largest value in an array by calling the private, helper method
max. Using big-Oh and a recurrence relation to justify your answer, what is the complexity of the
method call max(list) where list contains N elements?
public int max(int[] list){
return max(list,0,list.length-1);
}
private int max(int[] list, int leftIndex, int rightIndex){
if (leftIndex == rightIndex) return list[leftIndex];
int mid = (leftIndex + rightIndex)/2;
return Math.max(max(list,leftIndex,mid),max(list,mid+1,rightIndex));
}
What is the recurrence for the helper function max?
___ 1.
___ 2.
___ 3.
T(n) = 2T(n/2) + O(1)
T(n) = T(n/2) + O(n)
T(n) = 2T(n/2) + O(n)
What is the Big for this function (use the chart in the slides to figure it out)
The method findKth below returns the kth largest element in a binary search tree of N elements.
What is its complexity in the average case when trees are roughly balanced and in the worst case.
private int size(TreeNode root){
if (root == null) return 0;
return1 + size(root.left) + size(root.right);
}
public String findKth(TreeNode root, int k){
if (root == null) return null;
int leftCount = size(root.left);
if (leftCount == k) {
return root.info;
}
else if (k < leftCount){
return findKth(root.left,k);
}
else {
return findKth(root.right,k-leftCount - 1);
}
}
Recurrence in the average case?
1. T(n) = 2T(n/2) + O(1)
2. T(n) = T(n/2) + O(n)
3. T(n) = T(n/2) + O(1)
What is the Big O of this function, given that?
Recurrence in the worst case?
1. T(n) = T(n-1) + O(1)
2. T(n) = T(n-1) + O(n)
3. T(n) = 2T(n/2) + O(1)
What is the Big O of this function, given that?
Download