Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Wednesday, October 4, 2017

Maximum difference between node and its ancestor


Idea is to find minimum value in its left and right subtree and evaluate maximum difference.


Code:

int ans=Integer.MIN_VALUE;
    int maxU(Node root)
    {
        if(root==null)
return Integer.MAX_VALUE;
if(root.left==null && root.right==null)
return root.data;
int val=Math.min(maxU(root.left),maxU(root.right));
ans=Math.max(ans,root.data-val);
return Math.min(val,root.data);
    }
    
int maxDiff(Node root)
{
maxU(root);
return ans;
}

0 Comments:

Post a Comment

Stats