GATE 2012
82 questions
MCQ 821-mark 39 · 2-mark 43
Questions 31–35 of 82
The height of a tree is defined as the number of edges on the longest path in the tree. The function shown in the pseudocode below is invoked as height(root) to compute the height of a binary tree rooted at the tree pointer root.
int height (treeptr n)
{ if (n == NULL) return -1;
if (n -> left == NULL)
if (n -> right == NULL) return 0;
else return B1;
else { h1 = height (n -> left);
if (n -> right == NULL) return (1+h1);
else { h2 = height (n -> right);
return B2;
}
}
} The appropriate expressions for the two boxes B1 and B2 areAnswer: (A)
Look at each case in the code:
- Only a right child: the height is 1 + height(right) B1
- Both children present: the height is 1 + max(h1, h2) B2
Answer: B1: 1 + height(nright), B2: 1 + max(h1, h2)
- Only a right child: the height is 1 + height(right) B1
- Both children present: the height is 1 + max(h1, h2) B2
Answer: B1: 1 + height(nright), B2: 1 + max(h1, h2)
The worst case running time to search for an element in a balanced binary search tree with elements is
Answer: (C)
A search in a balanced BST needs time, where .
Simplify the log:
Answer:
Simplify the log:
Answer:
A list of n strings, each of length n, is sorted into lexicographic order using the merge-sort algorithm. The worst case running time of this computation is
Answer: (B)
Merge sort does comparisons. Comparing two strings of length n can cost O(n) each time.
Total time =
Answer:
Total time =
Answer:
Let W(n) and A(n) denote respectively, the worst case and average case running time of an algorithm executed on an input of size n. Which of the following is ALWAYS TRUE?
Answer: (C)
The average case is an average of running times over inputs of size , and each of them is at most the worst case. So for every , which means . This is always true.
The others can fail:
(A) fails for quicksort: but .
(B) fails for the same reason.
(D) fails when the two are the same order, for example merge sort, where both are .
Answer: (C)
The others can fail:
(A) fails for quicksort: but .
(B) fails for the same reason.
(D) fails when the two are the same order, for example merge sort, where both are .
Answer: (C)
The recurrence relation capturing the optimal execution time of the Towers of Hanoi problem with n discs is
Answer: (D)
First, shift the top n 1 discs to the spare peg. Next, make 1 move for the largest disc. Last, place the n 1 discs back on top of it.
This gives the recurrence:
T(n) = 2T(n 1) + 1
Answer: T(n) = 2T(n 1) + 1
This gives the recurrence:
T(n) = 2T(n 1) + 1
Answer: T(n) = 2T(n 1) + 1