Grokking 75: Top Coding Interview Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Maximum Difference Between Node and Ancestor (medium)
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Problem Statement

You are given the root of a binary tree. Each node in the tree has a unique value.

Find the maximum difference between the value of any node and the value of any ancestor of that node.

An ancestor of a node is any node on the path from the root to that node, excluding the node itself.

Examples

Example 1:

  • Input: [5, 3, 8, 1, 4, null, 10]
    5
   / \
  3   8
 / \   \
1   4  10

  • Output: 5
  • Explanation: The maximum difference is between node 10 and its ancestor node 5 (|10 - 5| = 5).

Example 2:

  • Input: [10, 6, 15, 4, 8, 12, 18]
   10
   /  \
  6   15
 /\   / \
4  8  12 18

  • Output: 8
  • Explanation: The maximum difference is between node 18 and its ancestor node 10 (|18 - 10| = 8).

Example 3:

  • Input: [8,3,10,1,6,null,14,null,null,4,7,13]
    8
   / \
  3   10
 / \   \
1   6   14
   /\   /
  4  7 13

  • Output: 7
  • Explanation: The maximum difference is between node 1 and its ancestor node 8 (|8 - 1| = 7).

Constraints:

  • The number of nodes in the tree is in the range [2, 5000].
  • 0 <= Node.val <= 10<sup>5</sup>

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible