albertonline· portal
blind75

Solving Maximum Depth of Binary Tree: Finding the Longest Path

Jan 14, 2024 · Exploring a solution to determine the maximum depth (or height) of a binary tree, which is the length of the longest path from the root down to the farthest leaf node.

The "Maximum Depth of Binary Tree" problem is focused on finding the maximum depth (or height) of a binary tree. The depth of a binary tree is the number of nodes along the longest path from the root node down to the farthest leaf node.

Problem Statement

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

Example

Consider a binary tree:

Binary Tree

The maximum depth of this tree is 3.

Solution Approach - Depth-First Search

typescript

Breaking Down the Solution


  • Recursive Approach: The solution uses a recursive depth-first search algorithm.
  • Base Case: If the node is null, the depth is 0.
  • Recursive Calculation: The depth of each subtree (left and right) is calculated, and the greater of the two depths is chosen, adding one to account for the current node.

Solution in Typescript one-liner

typescript

Conclusion


Determining the maximum depth of a binary tree is a fundamental problem in tree algorithms, emphasizing the use of recursion and understanding of tree traversal techniques.

Rust Solution

rust

Rust's Option<Box<TreeNode>> splits two concerns the TypeScript TreeNode | null conflates: Option carries the null-ness while Box supplies the heap indirection a self-referential struct needs to have a known size. The match on root replaces the null check entirely — the None arm returns 0, and the Some(node) arm binds the unwrapped node. Because max_depth takes &Option<Box<TreeNode>> by reference, recursing on &node.left and &node.right borrows each child rather than moving it, so the tree survives the traversal. Note that .max() is a method on the i32 result, not a free function.

Go Solution

go

Go models each child as a *TreeNode pointer, so the base case is a plain root == nil check that returns 0. Where the TypeScript one-liner leans on Math.max, this code spells the larger of the two out by hand with an explicit if l > r { return l + 1 } and a trailing return r + 1. The sample tree in main is assembled from nested composite literals like &TreeNode{val: 3, left: ...}, where & takes the address of each struct inline.

Comments (0)

Stub comments live in your browser only (localStorage). No server round-trip yet.

No comments yet. Be the first.