Data Structures
Trees
GATE 2012
Hard
The height of a tree is defined as the number of edges on the longest path in the tree. The function shown 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; // Box 1
else {
h1 = height(n->left);
if (n->right == NULL) return (1+h1);
else {
h2 = height(n->right);
return B2; // Box 2
}
}
}The appropriate expressions for the two boxes B1 and B2 are
- B1: (1+height(n->right)) B2: (1+max(h1,h2))
- BB1: (height(n->right)) B2: (1+max(h1,h2))
- CB1: height(n->right) B2: max(h1,h2)
- DB1: (1+height(n->right)) B2: max(h1,h2)
Explanation
Box 1 handles a node with only a right child: its height is 1 (the edge down) plus the height of the right subtree, so B1 = 1+height(n->right). Box 2 handles a node with both children: its height is 1 (the edge down) plus whichever child subtree is taller, so B2 = 1+max(h1,h2).
Source: GATE CS 2012 (2012)
This question is part of a 15-day revision cycle — sign in and Project Forge will bring it back the day before you'd forget it.