[Leetcode] Maximum Depth of Binary Tree

PHIL
Coding Memo
Published in
1 min readApr 27, 2022

A basic DFS tree problem.

Description

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

A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Examples

Example 1:

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

Example 2:

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

Solution

The fundemental element of DFS is deciding what to return and what to pass as parameter. The value related with the problem’s requirement may be kept in a global container or passed across recursion.

Consider base as none or only root node existent. Forward to bottom and start passing depth back. The val returned indicates depth of subtree and will be added like a prefix on val of upper recursion. The prefix shall be kept maximum between left & right preceding the accumulation.

  • code

ref: https://www.educative.io/edpresso/finding-the-maximum-depth-of-a-binary-tree

--

--

PHIL
Coding Memo

Jotting the ideas down in codes or articles