Similar questions 2 more →
Tree Properties & Traversals


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.