Maximum difference between node and its ancestor in Binary Tree | A binary tree node has key , pointer to left and right child ; Class Res created to implement pass by reference of ' res ' variable ; 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 ' ; Returning Maximum int value if node is not there ( one child case ) ; If leaf node then just return node 's value  ; Recursively calling left and right subtree for minimum value ; Updating res if ( node value - minimum value from subtree ) is bigger than res ; Returning minimum value got so far ; This function mainly calls maxDiffUtil ( ) ; Initialising result with minimum int value ; Helper function to print inorder traversal of binary tree ; Driver program to test the above functions ; Making above given diagram 's binary tree
class Node { int key ; Node left , right ; public Node ( int key ) { this . key = key ; left = right = null ; } } class Res { int r = Integer . MIN_VALUE ; } public class BinaryTree { Node root ; int maxDiffUtil ( Node t , Res res ) { if ( t == null ) return Integer . MAX_VALUE ; if ( t . left == null && t . right == null ) return t . key ; int val = Math . min ( maxDiffUtil ( t . left , res ) , maxDiffUtil ( t . right , res ) ) ; res . r = Math . max ( res . r , t . key - val ) ; return Math . min ( val , t . key ) ; } int maxDiff ( Node root ) { Res res = new Res ( ) ; maxDiffUtil ( root , res ) ; return res . r ; } void inorder ( Node root ) { if ( root != null ) { inorder ( root . left ) ; System . out . print ( root . key + " " ) ; inorder ( root . right ) ; } } public static void main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; 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 ( " Maximum ▁ difference ▁ between ▁ a ▁ node ▁ and " + " ▁ its ▁ ancestor ▁ is ▁ : ▁ " + tree . maxDiff ( tree . root ) ) ; } }