Diagonal Sum of a Binary Tree | Node Structure ; to map the node with level - index ; recursvise function to calculate sum of elements where level - index is same . ; if there is no child then return ; add the element in the group of node whose level - index is equal ; left child call ; right child call ; Function call ; for different values of level - index add te sum of those node to answer ; build binary tree ; Function Call ; print the daigonal sums
class Node { constructor ( data ) { this . data = data ; this . left = null ; this . right = null ; } } let grid = new Map ( ) ; function addConsideringGrid ( root , level , index ) { if ( root == null ) return ; if ( grid . has ( level - index ) ) { grid . set ( level - index , grid . get ( level - index ) + ( root . data ) ) ; } else { grid . set ( level - index , root . data ) ; } addConsideringGrid ( root . left , level + 1 , index - 1 ) ; addConsideringGrid ( root . right , level + 1 , index + 1 ) ; } function diagonalSum ( root ) { addConsideringGrid ( root , 0 , 0 ) ; let ans = [ ] ; for ( let [ key , value ] of grid ) { ans . push ( value ) ; } return ans ; } let root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . left . left = new Node ( 9 ) ; root . left . right = new Node ( 6 ) ; root . right . left = new Node ( 4 ) ; root . right . right = new Node ( 5 ) ; root . right . left . right = new Node ( 7 ) ; root . right . left . left = new Node ( 12 ) ; root . left . right . left = new Node ( 11 ) ; root . left . left . right = new Node ( 10 ) ; let v = diagonalSum ( root ) ; for ( let i = 0 ; i < v . length ; i ++ ) document . write ( v [ i ] + " " ) ;