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 var 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 var value ; * Helper function to prvar inorder traversal of binary tree ; Driver program to test the above functions Making above given diagram 's binary tree
class Node { constructor ( key ) { this . key = key ; this . left = this . right = null ; } } class Res { constructor ( ) { this . r = Number . MIN_VALUE ; } } var root ; function maxDiffUtil ( t , res ) { if ( t == null ) return Number . MAX_VALUE ; if ( t . left == null && t . right == null ) return t . key ; var 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 ) ; } function maxDiff ( root ) { res = new Res ( ) ; maxDiffUtil ( root , res ) ; return res . r ; } function inorder ( root ) { if ( root != null ) { inorder ( root . left ) ; document . write ( root . key + " " ) ; inorder ( root . right ) ; } } 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 ) ) ;