We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Maximum Difference Between Node and Ancestor

Difficulty: Medium


Problem Description

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.


Key Insights

  • The problem requires traversing the binary tree to explore all ancestor-descendant pairs.
  • The maximum difference can be calculated by keeping track of the minimum and maximum values encountered along the path from the root to each node.
  • A depth-first search (DFS) approach is suitable for exploring each path in the tree.

Space and Time Complexity

Time Complexity: O(N) - where N is the number of nodes in the tree, as we need to visit each node once. Space Complexity: O(H) - where H is the height of the tree, for the recursion stack.


Solution

To solve this problem, we can use a depth-first search (DFS) algorithm that traverses the tree. At each node, we keep track of the minimum and maximum values encountered from the root to that node. The difference between the current node's value and the recorded min/max values will give us potential maximum differences. We update the overall maximum difference as we traverse.


Code Solutions

def maxAncestorDiff(root):
    def dfs(node, min_val, max_val):
        if not node:
            return max_val - min_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(left_diff, right_diff)

    return dfs(root, root.val, root.val)
← Back to All Questions