Start learning free

LESSON 353 OF 445 · BINARY TREES

Maximum Depth of Binary Tree in Rust

Practice O(n)

Given the root of a binary tree, return its maximum depth.

The maximum depth of a binary tree is the number of nodes along the longest path from the root down to the farthest leaf. An empty tree has a depth of 0.

The trees below are written in level order (top to bottom, left to right), with None for a missing child.

 

Example 1:

    3
   / \
  9   20
     /  \
    15   7

Input: root = [3,9,20,None,None,15,7]
Output: 3
Explanation: The longest paths from the root to a leaf, 3 → 20 → 15 and 3 → 20 → 7, have 3 nodes each. The path 3 → 9 has only 2.

Example 2:

  1
   \
    2

Input: root = [1,None,2]
Output: 2
Explanation: The only path, 1 → 2, has 2 nodes.

Example 3:

Input: root = []
Output: 0
Explanation: An empty tree has no nodes, so its depth is 0.

 

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • Each node value is between -100 and 100.
  • The tree is at most 400 levels deep.

 

Follow up: Can you do it in O(n) time, visiting each of the n nodes only once?
STEP 1 OF 6
    Ctrl + Enter to check

    Maximum Depth Of Binary Tree in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free