Binary Trees Depth first: return a value up

344. Maximum Depth of Binary Tree

Easy 147 DSA Sheet

You are given root, the root node of a binary tree. Return the maximum depth of the tree.

A binary tree is made of nodes. Each node holds a value and has at most two children, a left child and a right child. A node with no children is a leaf. The maximum depth is the number of nodes on the longest path that starts at the root and goes down to a leaf. An empty tree has depth 0.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

357191215

Input: root = [7, 3, 12, null, 5, 9, 15, null, null, 1]

Output: 4

Explanation: The longest path from the root is 7 → 12 → 9 → 1, with 4 nodes. The path 7 → 3 → 5 has only 3 nodes.

Example 2

Input: root = []

Output: 0

Explanation: The tree has no nodes, so its depth is 0.

Example 3

-6-1-6

Input: root = [-6, null, -6, -1]

Output: 3

Explanation: Each node has one child, so the tree is a single path: −6, then −6 as its right child, then −1 as the left child of that node.

Check your understanding

Work out the answer for this input before you write any code.

root = [8, 4, 9, 2, 6, null, null, null, null, 5]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.