
Maximum Difference Between Node and Ancestor (medium)
Problem Statement
Given a root of the binary tree, return the maximum absolute difference in value between any node in a binary tree and its any ancestor.
A node a is the ancestor of node b if node a precedes node b in the path from the root to node b.
Examples
Example 1:
- Input: root =
[5, 3, 8, 0, null, 4, 7, 1]
- Expected Output:
5 - Justification: The maximum difference is between node 0 and its ancestor 5, which is 5.
Example 2:
- Input: root =
[2, 1, 3]
- Expected Output:
1 - Justification: There are two differences to consider: 2-1 and 3-2. Both differences are 1, so the maximum difference is 1.
Example 3:
- Input: root =
[8, 2, null, 1, 5]
- Expected Output:
7 - Justification: The maximum difference is between node 1 and its ancestor 8, which is 7.
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
.....
.....
.....
Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory