AlgoMaster Logo

Maximum Difference Between Node and Ancestor

Last Updated: November 14, 2025

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive DFS Approach

Intuition:

The problem is asking us to find the maximum difference between a node and its ancestor. This suggests a tree traversal technique where we either calculate the max difference for each node recursively or store the maximum/minimum value as we traverse.

Let's start by using a Depth-First Search (DFS) approach where for each node, we compute the maximum difference using its direct ancestors (i.e., the nodes along its path to the root).

Steps:

  1. Perform a DFS traversal starting from the root node.
  2. For each node, calculate the maximum difference between the node's value and the maximum and minimum values observed so far in the DFS path.
  3. Store and update the global maximum difference if it's greater than the previously recorded difference.
  4. Traverse both left and right children, updating the path's maximum and minimum values accordingly.

Code: