Last Updated: November 14, 2025
Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.
A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b.
Example 1:
Output: 7
Explanation: We have various ancestor-node differences, some of which are given below :
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
Output: 3
[2, 5000].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).