Grokking Tree Coding Patterns for Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Maximum Difference Between Node and Ancestor (medium)
On this page

Problem Statement

Examples

Try it yourself

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]
Image
  • 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]
Image
  • 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]
Image
  • 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

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!

On this page

Problem Statement

Examples

Try it yourself