The height of a tree is defined as the number of edges on the longest path in the tree. The function shown in the pseudo-code 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:
View worked solution
Answer: A
The height of a binary tree is defined as the number of edges on the longest path from the root to a leaf. By this definition:
- An empty tree (
NULL) has a height of . - A single-node tree (leaf) has a height of .
- For any node , its height is .
Let us analyze the cases in the given pseudo-code:
1. Determining Box 1 (B1)
This block is executed when n -> left == NULL but n -> right != NULL:
if(n -> left == NULL)
if(n -> right == NULL) return 0;
else return B1; // Box 1
Since the left child is empty and the right child exists, the height of the tree rooted at is plus the height of its right subtree. Therefore:
2. Determining Box 2 (B2)
This block is executed when both n -> left and n -> right are not NULL:
else{
h1 = height(n -> left);
if(n -> right == NULL) return (1+h1);
else{
h2 = height(n -> right);
return B2; // Box 2
}
}
Here, is the height of the left subtree and is the height of the right subtree. Since both subtrees exist, the height of the tree at is plus the maximum of the heights of the two subtrees. Therefore:
Thus, the correct expressions are:
- B1:
- B2:
Free practice · Your answers on this page are not saved.
