Finding the height of a binary tree recursively

The height of a node in a binary tree is simply the maximum of the height of its left and right subtrees, plus one.

This lends itself to a simple recursive algorithm for finding the height of a binary tree.

static int max(int a, int b)
{
    if (a >= b) {
        return a;
    }
    return b;
}

unsigned int binarytree_height_recursive(const btnode *node)
{
    unsigned int height = 0;
    if (node->left || node->right) {
        height = max(node->left ? binarytree_height_recursive(node->left) : 0,
                node->right ? binarytree_height_recursive(node->right) : 0) + 1;
    }
    return height;
}

unsigned int binarytree_height(const binarytree *tree)
{
	unsigned int height = 0;
	if (tree->root) {
		height = binarytree_height_recursive(tree->root);
	}
	return height;
}

Related