Calculate binary-tree height
Calculate the height of a binary tree as the number of nodes on its longest root-to-leaf path. An empty tree has height zero.
Course progress
Problem 45 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
tree = 8 with children 4 and 12; node 4 has child 2
Expected output
3
What is happening?
The longest root-to-leaf path is 8 -> 4 -> 2. It contains three nodes, so the tree height is 3.
Solution strategy
Build the right mental model
Recursively calculate the left and right subtree heights, choose the larger one, and add one for the current node.
Core concepts
binary tree · recursion
Complexity
Time O(n), call-stack space O(h), where h is the tree height.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for binary-tree-height
using System;
class Program
{
class Node
{
public int Value { get; private set; }
public Node Left { get; set; }
public Node Right { get; set; }
public Node(int value) { Value = value; }
}
static int Height(Node node)
{
if (node == null) return 0;
return 1 + Math.Max(Height(node.Left), Height(node.Right));
}
static void Main()
{
Node root = new Node(8);
root.Left = new Node(4);
root.Right = new Node(12);
root.Left.Left = new Node(2);
Console.WriteLine(Height(root));
}
}Knowledge check
Questions students often ask
What is the main idea behind calculate binary-tree height?
Recursively calculate the left and right subtree heights, choose the larger one, and add one for the current node.
What is the time and space complexity of this solution?
Time O(n), call-stack space O(h), where h is the tree height.
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.