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
.
For example:
Consider the following binary tree:
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
In this tree, we have various ancestor-node differences. Some of these are:
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value is 7
obtained by |8 - 1| = 7
.
As another example, consider:
1
\
2
\
0
\
3
Here the answer is 3 (e.g. |0 - 3|)
Write a function that takes the root of a binary tree and returns the maximum absolute difference between the values of any ancestor and descendant nodes.
Given the root of a binary tree, the goal is to find the maximum absolute difference v
between the values of two different nodes a
and b
, where a
is an ancestor of b
. A node a
is considered an ancestor of b
if b
is a descendant of a
.
The most straightforward approach is to traverse the tree and, for each node, check all its descendants to find the maximum difference. This would involve a nested traversal, resulting in a higher time complexity.
Complexity Analysis:
A more efficient approach involves traversing the tree while keeping track of the minimum and maximum values encountered along the path from the root to the current node. This way, for each node, we can calculate the maximum possible difference with its ancestors in O(1) time.
min_val
and max_val
:
min_val
and max_val
.min_val
and max_val
as we go.Code Implementation (Python):
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def maxAncestorDiff(root: TreeNode) -> int:
def dfs(node, min_val, max_val):
if not node:
return 0
max_diff = max(abs(node.val - min_val), abs(node.val - max_val))
min_val = min(min_val, node.val)
max_val = max(max_val, node.val)
left_diff = dfs(node.left, min_val, max_val)
right_diff = dfs(node.right, min_val, max_val)
return max(max_diff, left_diff, right_diff)
return dfs(root, root.val, root.val)
Complexity Analysis:
[2, 5000]
, so this case will not happen.