Diagonal Sum of a Binary Tree | Java Program to calculate the sum of diagonal nodes . ; Node Structure ; to map the node with level - index ; Function to create new node ; 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 ; Driver code ; build binary tree ; Function Call ; print the daigonal sums
import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } ; static HashMap < Integer , Integer > grid = new HashMap < > ( ) ; static Node newNode ( int data ) { Node Node = new Node ( ) ; Node . data = data ; Node . left = Node . right = null ; return Node ; } static void addConsideringGrid ( Node root , int level , int index ) { if ( root == null ) return ; if ( grid . containsKey ( level - index ) ) grid . put ( level - index , grid . get ( level - index ) + ( root . data ) ) ; else grid . put ( level - index , root . data ) ; addConsideringGrid ( root . left , level + 1 , index - 1 ) ; addConsideringGrid ( root . right , level + 1 , index + 1 ) ; } static Vector < Integer > diagonalSum ( Node root ) { grid . clear ( ) ; addConsideringGrid ( root , 0 , 0 ) ; Vector < Integer > ans = new Vector < > ( ) ; for ( Map . Entry < Integer , Integer > x : grid . entrySet ( ) ) { ans . add ( x . getValue ( ) ) ; } return ans ; } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 9 ) ; root . left . right = newNode ( 6 ) ; root . right . left = newNode ( 4 ) ; root . right . right = newNode ( 5 ) ; root . right . left . right = newNode ( 7 ) ; root . right . left . left = newNode ( 12 ) ; root . left . right . left = newNode ( 11 ) ; root . left . left . right = newNode ( 10 ) ; Vector < Integer > v = diagonalSum ( root ) ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) System . out . print ( v . get ( i ) + " ▁ " ) ; } }