VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-difference-between-node-and-its-ancestor-in-binary-tree/

⇱ Maximum difference between node and its ancestor in Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum difference between node and its ancestor in Binary Tree

Last Updated : 23 Jul, 2025

Given a Binary tree, The task is to find the maximum value by subtracting the value of node B from the value of node A, where A and B are two nodes of the binary tree and A is an ancestor of B.

Examples:

Input:

πŸ‘ tree

Output: 7
Explanation: We can have various ancestor-node difference, some of which are given below : 
8 – 3 = 5 , 3 – 7 = -4, 8 – 1 = 7, 10 – 13 = -3
Among all those differences maximum value is 7 obtained by subtracting 1 from 8, which we need to return as result. 

Input:
            9
          /  \
        6    3
            /  \
          1    4
Output: 8

Approach:

Traverse whole binary tree to get max difference and we can obtain the result in one traversal only by following below steps : 

  • If current node is a leaf node then just return its value because it can’t be ancestor of any node. 
  • Then at each internal node try to get minimum value from left subtree and right subtree and calculate the difference between node value and this minimum value and according to that update the result. 

Follow the below steps to Implement the idea:

  • Recursively traverse every node (say t) of the tree:
    • If t = NULL return INT_MAX
    • If the current node is the leaf node then just return the node's value.
    • Recursively calling for left and right subtree for minimum value
      • Update res if node value - minimum value from subtree is bigger than res i.e res = max(*res, t->key - val).
    • Return minimum value got so far i.e. return min(val, t->key);.

Below is the implementation of the above idea.


Output
7

Time Complexity: O(N), for visiting every node of the tree.
Auxiliary Space: O(N) for recursion call stack.

Comment
Article Tags:
Article Tags: