Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum difference between node and its ancestor in Binary Tree
Next article icon

Maximum difference between node and its ancestor in Binary Tree

Last Updated : 13 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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

Recommended Practice
Maximum difference between node and its ancestor
Try It!

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.

C++
// C++ program to find maximum difference between node // and its ancestor #include <bits/stdc++.h> using namespace std;  /* A binary tree node has key, pointer to left    child and a pointer to right child */ struct Node {     int key;     struct Node *left, *right; };  /* To create a newNode of tree and return pointer */ struct Node* newNode(int key) {     Node* temp = new Node;     temp->key = key;     temp->left = temp->right = NULL;     return (temp); }  /* Recursive function to calculate maximum ancestor-node    difference in  binary tree. It updates value at 'res'    to store the result.  The returned value of this function    is minimum value in subtree rooted with 't' */ int maxDiffUtil(Node* t, int* res) {     /* Returning Maximum int value if node is not        there (one child case)  */     if (t == NULL)         return INT_MAX;      /* If leaf node then just return node's value  */     if (t->left == NULL && t->right == NULL)         return t->key;      /* Recursively calling left and right subtree        for minimum value  */     int val = min(maxDiffUtil(t->left, res),                   maxDiffUtil(t->right, res));      /* Updating res if (node value - minimum value        from subtree) is bigger than res  */     *res = max(*res, t->key - val);      /* Returning minimum value got so far */     return min(val, t->key); }  /* This function mainly calls maxDiffUtil() */ int maxDiff(Node* root) {     // Initialising result with minimum int value     int res = INT_MIN;      maxDiffUtil(root, &res);      return res; }  /* Helper function to print inorder traversal of   binary tree   */ void inorder(Node* root) {     if (root) {         inorder(root->left);         cout << root->key << " ";         inorder(root->right);     } }  // Driver program to test above functions int main() {     // Making above given diagram's binary tree     Node* root;     root = newNode(8);     root->left = newNode(3);      root->left->left = newNode(1);     root->left->right = newNode(6);     root->left->right->left = newNode(4);     root->left->right->right = newNode(7);      root->right = newNode(10);     root->right->right = newNode(14);     root->right->right->left = newNode(13);      cout << maxDiff(root); } 
Java
/* Java program to find maximum difference between node    and its ancestor */  // A binary tree node has key, pointer to left // and right child class Node {     int key;     Node left, right;      public Node(int key)     {         this.key = key;         left = right = null;     } }  /* Class Res created to implement pass by reference    of 'res' variable */ class Res {     int r = Integer.MIN_VALUE; }  public class BinaryTree {     Node root;      /* Recursive function to calculate maximum ancestor-node        difference in  binary tree. It updates value at 'res'        to store the result.  The returned value of this        function        is minimum value in subtree rooted with 't' */     int maxDiffUtil(Node t, Res res)     {         /* Returning Maximum int value if node is not            there (one child case)  */         if (t == null)             return Integer.MAX_VALUE;          /* If leaf node then just return node's value  */         if (t.left == null && t.right == null)             return t.key;          /* Recursively calling left and right subtree            for minimum value  */         int val = Math.min(maxDiffUtil(t.left, res),                            maxDiffUtil(t.right, res));          /* Updating res if (node value - minimum value            from subtree) is bigger than res  */         res.r = Math.max(res.r, t.key - val);          /* Returning minimum value got so far */         return Math.min(val, t.key);     }      /* This function mainly calls maxDiffUtil() */     int maxDiff(Node root)     {         // Initialising result with minimum int value         Res res = new Res();         maxDiffUtil(root, res);          return res.r;     }      /* Helper function to print inorder traversal of        binary tree   */     void inorder(Node root)     {         if (root != null) {             inorder(root.left);             System.out.print(root.key + "");             inorder(root.right);         }     }      // Driver program to test the above functions     public static void main(String[] args)     {         BinaryTree tree = new BinaryTree();          // Making above given diagram's binary tree         tree.root = new Node(8);         tree.root.left = new Node(3);         tree.root.left.left = new Node(1);         tree.root.left.right = new Node(6);         tree.root.left.right.left = new Node(4);         tree.root.left.right.right = new Node(7);          tree.root.right = new Node(10);         tree.root.right.right = new Node(14);         tree.root.right.right.left = new Node(13);          System.out.println(tree.maxDiff(tree.root));     } }  // This code has been contributed by Mayank // Jaiswal(mayank_24) 
Python3
# Python3 program to find maximum difference # between node and its ancestor  _MIN = -2147483648 _MAX = 2147483648  # Helper function that allocates a new # node with the given data and None left # and right pointers.   class newNode:      # Constructor to create a new node     def __init__(self, key):         self.key = key         self.left = None         self.right = None   """  Recursive function to calculate maximum  ancestor-node difference in binary tree.  It updates value at 'res' to store the  result. The returned value of this function is minimum value in subtree rooted with 't' """   def maxDiffUtil(t, res):     """ Returning Maximum value if node     is not there (one child case) """     if (t == None):         return _MAX, res      """ If leaf node then just return         node's value """     if (t.left == None and t.right == None):         return t.key, res      """ Recursively calling left and right      subtree for minimum value """     a, res = maxDiffUtil(t.left, res)     b, res = maxDiffUtil(t.right, res)     val = min(a, b)      """ Updating res if (node value - minimum      value from subtree) is bigger than res """     res = max(res, t.key - val)      """ Returning minimum value got so far """     return min(val, t.key), res   """ This function mainly calls maxDiffUtil() """   def maxDiff(root):      # Initialising result with minimum value     res = _MIN     x, res = maxDiffUtil(root, res)     return res   """ Helper function to print inorder traversal of binary tree """   def inorder(root):      if (root):          inorder(root.left)         prf("%d ", root.key)         inorder(root.right)   # Driver Code if __name__ == '__main__':      """      Let us create Binary Tree shown     in above example """     root = newNode(8)     root.left = newNode(3)      root.left.left = newNode(1)     root.left.right = newNode(6)     root.left.right.left = newNode(4)     root.left.right.right = newNode(7)      root.right = newNode(10)     root.right.right = newNode(14)     root.right.right.left = newNode(13)     print(maxDiff(root))  # This code is contributed by # Shubham Singh(SHUBHAMSINGH10) 
C#
using System;  /* C# program to find maximum difference between node    and its ancestor */  // A binary tree node has key, pointer to left // and right child public class Node {     public int key;     public Node left, right;      public Node(int key)     {         this.key = key;         left = right = null;     } }  /* Class Res created to implement pass by reference    of 'res' variable */ public class Res {     public int r = int.MinValue; }  public class BinaryTree {     public Node root;      /* Recursive function to calculate maximum ancestor-node        difference in  binary tree. It updates value at 'res'        to store the result.  The returned value of this        function        is minimum value in subtree rooted with 't' */     public virtual int maxDiffUtil(Node t, Res res)     {         /* Returning Maximum int value if node is not            there (one child case)  */         if (t == null) {             return int.MaxValue;         }          /* If leaf node then just return node's value  */         if (t.left == null && t.right == null) {             return t.key;         }          /* Recursively calling left and right subtree            for minimum value  */         int val = Math.Min(maxDiffUtil(t.left, res),                            maxDiffUtil(t.right, res));          /* Updating res if (node value - minimum value            from subtree) is bigger than res  */         res.r = Math.Max(res.r, t.key - val);          /* Returning minimum value got so far */         return Math.Min(val, t.key);     }      /* This function mainly calls maxDiffUtil() */     public virtual int maxDiff(Node root)     {         // Initialising result with minimum int value         Res res = new Res();         maxDiffUtil(root, res);          return res.r;     }      /* Helper function to print inorder traversal of        binary tree   */     public virtual void inorder(Node root)     {         if (root != null) {             inorder(root.left);             Console.Write(root.key + "");             inorder(root.right);         }     }      // Driver program to test the above functions     public static void Main(string[] args)     {         BinaryTree tree = new BinaryTree();          // Making above given diagram's binary tree         tree.root = new Node(8);         tree.root.left = new Node(3);         tree.root.left.left = new Node(1);         tree.root.left.right = new Node(6);         tree.root.left.right.left = new Node(4);         tree.root.left.right.right = new Node(7);          tree.root.right = new Node(10);         tree.root.right.right = new Node(14);         tree.root.right.right.left = new Node(13);          Console.WriteLine(tree.maxDiff(tree.root));     } }  // This code is contributed by Shrikant13 
JavaScript
<script> /* javascript program to find maximum difference between node    and its ancestor */  // A binary tree node has key, pointer to left  // and right child  class Node {     constructor(key) {         this.key = key;         this.left = this.right = null;     } }  /*  * Class Res created to implement pass by reference of 'res' variable  */ class Res { constructor(){     this.r = Number.MIN_VALUE;     } }  var root;      /*      * Recursive function to calculate maximum ancestor-node difference in binary      * tree. It updates value at 'res' to store the result. The returned value of      * this function is minimum value in subtree rooted with 't'      */     function maxDiffUtil( t,  res) {         /*          * Returning Maximum var value if node is not there (one child case)          */         if (t == null)             return Number.MAX_VALUE;          /* If leaf node then just return node's value */         if (t.left == null && t.right == null)             return t.key;          /*          * Recursively calling left and right subtree for minimum value          */         var val = Math.min(maxDiffUtil(t.left, res), maxDiffUtil(t.right, res));          /*          * Updating res if (node value - minimum value from subtree) is bigger than res          */         res.r = Math.max(res.r, t.key - val);          /* Returning minimum value got so far */         return Math.min(val, t.key);     }      /* This function mainly calls maxDiffUtil() */     function maxDiff( root) {         // Initialising result with minimum var value          res = new Res();         maxDiffUtil(root, res);          return res.r;     }      /*      * Helper function to print inorder traversal of binary tree      */     function inorder( root) {         if (root !=null) {             inorder(root.left);             document.write(root.key + "");             inorder(root.right);         }     }      // Driver program to test the above functions                // Making above given diagram's binary tree         root = new Node(8);         root.left = new Node(3);         root.left.left = new Node(1);         root.left.right = new Node(6);         root.left.right.left = new Node(4);         root.left.right.right = new Node(7);          root.right = new Node(10);         root.right.right = new Node(14);         root.right.right.left = new Node(13);          document.write(maxDiff(root));  // This code contributed by umadevi9616  </script> 

Output
7

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


Next Article
Maximum difference between node and its ancestor in Binary Tree

U

Utkarsh Trivedi
Improve
Article Tags :
  • Tree
  • DSA
  • Amazon
Practice Tags :
  • Amazon
  • Tree

Similar Reads

    Maximum difference between node and its ancestor in a Directed Acyclic Graph ( DAG )
    Given a 2D array Edges[][], representing a directed edge between the pair of nodes in a Directed Acyclic Connected Graph consisting of N nodes valued from [1, N] and an array arr[] representing weights of each node, the task is to find the maximum absolute difference between the weights of any node
    8 min read
    Maximum absolute difference between the sibling nodes of given BST
    Given a BST (Binary Search Tree) with N Nodes, the task is to find the maximum absolute difference between the sibling nodes. Two nodes are said to be siblings if they are present at the same level, and their parents are the same.] Examples: Input: Diagram 1 for Ex-1 Output: 70Explanation:105 - 50 =
    8 min read
    Find the maximum node at a given level in a binary tree
    Given a Binary Tree and a Level. The task is to find the node with the maximum value at that given level. The idea is to traverse the tree along depth recursively and return the nodes once the required level is reached and then return the maximum of left and right subtrees for each subsequent call.
    13 min read
    Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
    Given an N-ary tree with weighted edge and Q queries where each query contains two nodes of the tree. The task is to find the maximum weighted edge in the simple path between these two nodes.Examples: Naive Approach: A simple solution is to traverse the whole tree for each query and find the path be
    15 min read
    Get maximum left node in binary tree
    Given a tree, the task is to find the maximum in an only left node of the binary tree. Examples: Input : 7 / \ 6 5 / \ / \ 4 3 2 1 Output : 6 Input : 1 / \ 2 3 / / \ 4 5 6 \ / \ 7 8 9 Output : 8 Traverse with inorder traversal and Apply the condition for the left node only and get maximum of left no
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences