data-structures · intermediate · ~15 min
Recurse over a binary tree.
Measure the height of a binary tree.
Given the node type typedef struct tnode { int v; struct tnode *l, *r; } tnode_t;, implement int tree_height(tnode_t *root) that returns the tree's height: the number of nodes on the longest path from the root down to a leaf.
root: a pointer to the root node (the type tnode_t is given, with an int v and left/right child pointers l and r). May be NULL.
int: the height. An empty tree (NULL) has height 0; a single node has height 1.
NULL -> 0
single node -> 1
root with depth-3 branch -> 3
root: pointer to a tnode_t (given: int v; tnode_t *l, *r;); may be NULL.
int: number of nodes on the longest root-to-leaf path (0 if empty).
typedef struct tnode { int v; struct tnode *l, *r; } tnode_t;
int tree_height(tnode_t *root) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.