Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Compute tree height

Find the height of a binary tree (empty tree height = 0).

Python practice8 minTrees & Binary TreesBeginnerLast updated March 29, 2026

Problem statement

Given the root of a binary tree, compute its height. Define the height as the number of nodes on the longest root-to-leaf path. For an empty tree (root is None), the height is 0. You should implement compute_height(root) that returns an integer height.

Task

Implement a function that returns the height (maximum number of nodes from root to any leaf) of a binary tree.

Examples

Small balanced tree

Input

compute_height(TreeNode(1, TreeNode(2), TreeNode(3)))

Output

2

Root plus one level of children -> height is 2.

Input format

A single argument: root (TreeNode or None).

Output format

An integer representing the tree height.

Constraints

- Number of nodes up to a few thousand (recursive or iterative solutions acceptable). - You may assume TreeNode values are integers but values do not affect height.

Samples

Sample 1

Input

compute_height(None)

Output

0

Empty tree has height 0.