CodePark/ problems / Maximum Depth of a Binary Tree
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Trees: depth-first and breadth-first

Maximum Depth of a Binary Tree

easyabout 10 minutes in an interview

Given the root of a binary tree, return how tall it is. Start at the root and walk down to a node with no children (a leaf). Count the nodes on the longest such walk. That count is the tree's maximum depth.

  • An empty tree (root is null) has depth 0.
  • A tree that is just a root has depth 1.
  • The tree can have up to 1,000 nodes, and it may lean heavily to one side.

Each node is a TreeNode with val, left and right. The starter already exports this class.

Input: root = [3, 9, 20, null, null, 15, 7] Output: 3The longest path is 3 → 20 → 15. The path 3 → 20 → 7 is just as long.
Input: root = [1, null, 2] Output: 2
Input: root = [] Output: 0