Maximum Difference Between Node and Ancestor — LeetCode 1026 Python Solution

MediumTreeDepth-First SearchBinary Tree
Problem
#1026
Reading time
4 min

The 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.

Example

Input
root = [8,3,10,1,6,null,14,null,null,4,7,13]
Output
7
Explanation
We have various ancestor-node differences, some of which are given below :

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:
        def dfs(root: Optional[TreeNode], mi: int, mx: int):
            if root is None:
                return
            nonlocal ans
            ans = max(ans, abs(mi - root.val), abs(mx - root.val))
            mi = min(mi, root.val)
            mx = max(mx, root.val)
            dfs(root.left, mi, mx)
            dfs(root.right, mi, mx)

        ans = 0
        dfs(root, root.val, root.val)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1026. Maximum Difference Between Node and Ancestor is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1026. Maximum Difference Between Node and Ancestor?
LeetCode 1026. Maximum Difference Between Node and Ancestor is rated Medium on LeetCode.
What is the time complexity of LeetCode 1026. Maximum Difference Between Node and Ancestor?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1026. Maximum Difference Between Node and Ancestor?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1026. Maximum Difference Between Node and Ancestor cover?
LeetCode 1026. Maximum Difference Between Node and Ancestor is tagged Tree, Depth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview