Maximum Difference Between Node and Ancestor in C++

Suppose we have the root of a binary tree, we have to find the maximum value V for which there exists different nodes A and B where V = |value of A – value of B| and A is an ancestor of B. So if the tree is like −

Then the output will be 7. The ancestor node differences are like [(8 - 3), (7 - 3), (8 - 1), (10-13)], among them the (8 - 1) = 7 is the maximum.

To solve this, we will follow these steps −

  • initially define ans 0

  • define one method called solve(), this will take the tree node, currMin and currMax. This will act as follows −

  • if node is null, then return

  • ans := maximum of ans, |value of node - currMin|, |value of node - currMax|

  • solve(left of node, minimum of node value and currMin, maximum of node value and currMax)

  • solve(right of node, minimum of node value and currMin, maximum of node value and currMax)

  • In the main section, call solve(root, value of root, value of root), and return ans

Let us see the following implementation to get better understanding −


 Live Demo

#include <bits/stdc++.h>
using namespace std;
class TreeNode{
   int val;
   TreeNode *left, *right;
      TreeNode(int data){
      val = data;
      left = NULL;
      right = NULL;
void insert(TreeNode **root, int val){
   queue<TreeNode*> q;
      TreeNode *temp = q.front();
         if(val != NULL)
            temp->left = new TreeNode(val);
            temp->left = new TreeNode(0);
         if(val != NULL)
            temp->right = new TreeNode(val);
            temp->right = new TreeNode(0);
TreeNode *make_tree(vector<int> v){
   TreeNode *root = new TreeNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      insert(&root, v[i]);
   return root;
class Solution {
   int ans;
   void solve(TreeNode* node, int currMin, int currMax){
      if (!node || node->val == 0) return;
      ans = max({ans, abs(node->val - currMin), abs(node->val -
      solve(node->left, min(node->val, currMin), max(node->val,
      solve(node->right, min(node->val, currMin), max(node->val,
   int maxAncestorDiff(TreeNode* root) {
      ans = 0;
      solve(root, root->val, root->val);
      return ans;
   vector<int> v = {8,3,10,1,6,NULL,14,NULL,NULL,4,7,13};
   TreeNode *root = make_tree(v);
   Solution ob;
   cout << (ob.maxAncestorDiff(root));





Updated on: 02-May-2020


Kickstart Your Career

Get certified by completing the course

Get Started