-
Notifications
You must be signed in to change notification settings - Fork 0
/
Diagonal Sum In Binary Tree
42 lines (33 loc) · 1.04 KB
/
Diagonal Sum In Binary Tree
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*Complete the function below
Node is as follows:
class Node{
int data;
Node left,right;
Node(int d){
data=d;
left=right=null;
}
}
*/
class Tree {
public static ArrayList <Integer> diagonalSum(Node root) {
int height = diagonalHeightUtil(root, 0);
ArrayList<Integer> res = new ArrayList<> ();
for(int i = 0; i < height; i++)
res.add(0);
diagonalSumUtil(root, 0, res);
return res;
}
private static int diagonalHeightUtil(Node root, int height) {
if(root == null)
return height;
return Math.max(diagonalHeightUtil(root.left, height + 1), diagonalHeightUtil(root.right, height));
}
private static void diagonalSumUtil(Node root, int height, ArrayList<Integer> res) {
if(root == null)
return ;
res.set(height, res.get(height) + root.data);
diagonalSumUtil(root.right, height, res);
diagonalSumUtil(root.left, height + 1, res);
}
}