Skip to main content
All Questions

Calculate the height of a binary tree.

Easy

Given the root of a binary tree, return its maximum depth: the number of nodes along the longest path from the root down to a leaf.

Trees in the examples and tests are written in level order, with null for a missing child.

Example 1

Input: root = [3, 9, 20, null, null, 15, 7] Output: 3 3 / \ 9 20 / \ 15 7

The longest paths, such as 3 -> 20 -> 15, have three nodes.

Example 2

Input: root = [1, null, 2] Output: 2

Constraints

  • The tree has between 0 and 10^4 nodes.
  • -100 <= Node.val <= 100

Related courses

Course

Machine Learning Engineer Interview Prep

Land your dream machine learning role at Meta, Google, Amazon, Apple, Microsoft, Nvidia, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Explore ML system design, core concepts, coding, behavioral interviews, and more.

Course

Data Engineering Interview Prep

Land your dream data engineering role at Meta, Google, Amazon, Microsoft, Walmart, DoorDash, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Practice data modeling, pipeline design, SQL, coding, behavioral interviews, and more.