GATE / CS ARCHIVE

GATE CSE 2001 / QUESTION 14(c)

Complete recursive tree depth

Data Structures · Tree Properties & Traversals · Full GATE CSE 2001 paper

GATE 2001, Q14(c) Descriptive
Report issue

Tree Properties & Traversals

Question 14(c), GATE 2001: depth(t) returns 0 for NULL, sets x=depth(t->left), then needs S1, S2 and S3 to return the tree depth.
Question 14(c), GATE 2001: depth(t) returns 0 for NULL, sets x=depth(t->left), then needs S1, S2 and S3 to return the tree depth.
Tap to enlarge
Answer & solution

Answer: S1: y=depth(t->right); S2: x+1; S3: y+1. (no official key was published)

The null-tree base case fixes depth as the number of nodes on a longest root-to-leaf path. Each nonempty tree contributes its root plus the larger child depth. Full compilable function:

#include <stddef.h>
typedef struct node {
    int key;
    struct node *left, *right;
} *Tree;
int depth(Tree t) {
    int x, y;
    if (t == NULL) return 0;
    x = depth(t->left);
    y = depth(t->right); /* S1 */
    if (x > y) return x + 1; /* S2 */
    else return y + 1; /* S3 */
}

A leaf returns 1. The preceding tree returns 4. Each node is visited once, giving O(n) time and O(h) recursive stack space; an edge-count definition would require a different base case and is not the convention of the supplied program.

Original paper, page 9