Maximum Difference Between Node and Ancestor
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.

The simplest solution is to bruteforce every node and calculate the sum. This takes O(n^2) time. But, can we do better?
Since the problem asks us the Maximum Difference, maybe we do not need to compare all ancestor for a given node and we only need to compare the ancestors with Maximum value and Minimum value.
Therefore, for a given node, we only need the maximum value and the minimum value from the root to this node.
To achieve this, we can define a function helper to start recursion, which receives a node and two integers, the maximum and minimum value of its ancestors, as input.
In the function helper, we need to update the maximum difference, the current maximum value, and the current minimum value.
Step 1: Initialize a variable result to record the required maximum difference.
Step 2: Define a function helper, which takes three arguments as input.
The first argument is the current node, and the second and third arguments are the maximum and minimum values along the root to the current node, respectively.
In the function
helper, updateresultand callhelperon the left and right subtrees.
Step 3: Run helper on the root. It will automatically do recursion on every node.
Step 4: Finally, return result.
Or a cleaner solution thanks to https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/274654/PythonJava-Recursion
Last updated
Was this helpful?