Replace each node of a Binary Tree with the sum of all the nodes present in its diagonal | Structure of a tree node ; Store sum of nodes at each diagonal of the tree ; Function to replace each node with the sum of nodes at the same diagonal ; IF root is NULL ; Replace nodes ; Traverse the left subtree ; Traverse the right subtree ; Function to find the sum of all the nodes at each diagonal of the tree ; If root is not NULL ; If update sum of nodes at current diagonal ; Traverse the left subtree ; Traverse the right subtree ; Function to print the nodes of the tree using level order traversal ; Stores node at each level of the tree ; Stores count of nodes at current level ; Stores front element of the queue ; Insert left subtree ; Insert right subtree ; Update length ; Build tree ; Find sum of nodes at each diagonal of the tree ; Replace nodes with the sum of nodes at the same diagonal ; Print tree
class TreeNode { constructor ( x ) { this . left = null ; this . right = null ; this . val = x ; } } let diagMap = new Map ( ) ; function replaceDiag ( root , d ) { if ( root == null ) return ; if ( diagMap . has ( d ) ) root . val = diagMap . get ( d ) ; replaceDiag ( root . left , d + 1 ) ; replaceDiag ( root . right , d ) ; } function getDiagSum ( root , d ) { if ( root == null ) return ; if ( diagMap . has ( d ) ) diagMap . set ( d , diagMap . get ( d ) + root . val ) ; else diagMap . set ( d , root . val ) ; getDiagSum ( root . left , d + 1 ) ; getDiagSum ( root . right , d ) ; } function levelOrder ( root ) { let q = [ ] ; q . push ( root ) ; while ( true ) { let length = q . length ; if ( ! length ) break ; while ( length ) { let temp = q [ 0 ] ; q . shift ( ) ; document . write ( temp . val + " " ) ; if ( temp . left != null ) q . push ( temp . left ) ; if ( temp . right != null ) q . push ( temp . right ) ; length -= 1 ; } } } let root = new TreeNode ( 5 ) ; root . left = new TreeNode ( 6 ) ; root . right = new TreeNode ( 3 ) ; root . left . left = new TreeNode ( 4 ) ; root . left . right = new TreeNode ( 9 ) ; root . right . right = new TreeNode ( 2 ) ; getDiagSum ( root , 0 ) ; replaceDiag ( root , 0 ) ; levelOrder ( root ) ;