Problem
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
.
Examples
Example 1:
graph TD H(8) H --- C(3) & J(10) C(3) --- A(1) C(3) --- F(6) F --- D(4) & G(7) J ~~~ N1:::hidden J --- N(14) N --- M(13) N ~~~ N2:::hidden classDef hidden display:none
|
|
Example 2:
graph TD A(1) A ~~~ N1:::hidden A --- B(2) B ~~~ N2:::hidden B --- F(0) F --- C(3) F ~~~ N3:::hidden classDef hidden display:none
|
|
Solution
Method 1 - DFS
To solve this problem, we need to find the maximum difference between the values of a
and b
such that a
is an ancestor of b
in a binary tree. This essentially requires traversing the tree while keeping track of the minimum and maximum values encountered along the path from the root to each node. The difference between these values at any point will help in determining the desired v
.
The main idea is a depth-first traversal (DFS), where we recursively explore the tree, updating the minimum and maximum values encountered so far.
Here is the approach:
- Start at the root and initialise the current minimum (
cur_min
) and maximum (cur_max
) to the root’s value. - For each child node, update the current minimum and maximum based on the child’s value, and compute the absolute difference between the node’s value and the current minimum or maximum.
- Propagate the updated values down the tree.
- Keep track of the global maximum difference (
ans
) using these values. - Base Case:
- If the node is
null
, return immediately (there’s no further subtree to explore).
- If the node is
- Recursive Calculations:
- Calculate the max difference for the left and right subtrees.
- Add the returned values to the overall result.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
. Each node is visited exactly once during the DFS traversal of the tree. - 🧺 Space complexity:
O(h)
. The recursion depth will be equal to the height of the binary tree (h
). In the worst case,h = n
for a skewed tree.