-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiagonal sum in binary tree.java
More file actions
50 lines (45 loc) · 1.21 KB
/
Copy pathDiagonal sum in binary tree.java
File metadata and controls
50 lines (45 loc) · 1.21 KB
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
43
44
45
46
47
48
49
50
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
class Node {
int data;
Node left, right;
Node(int d) {
data = d;
left = right = null;
}
}
class Pair<T, F> {
T first;
F second;
Pair(T first, F second) {
this.first = first;
this.second = second;
}
}
class Tree {
public static ArrayList<Integer> diagonalSum(Node root) {
Queue<Pair<Node, Integer>> q = new LinkedList<>();
q.add(new Pair(root, 0));
Map<Integer, Integer> hash = new HashMap<>();
while (!q.isEmpty()) {
Node node = q.peek().first;
int diag = q.peek().second;
q.poll();
hash.put(diag, hash.getOrDefault(diag, 0) + node.data);
if (node.left != null) {
q.add(new Pair(node.left, diag + 1));
}
if (node.right != null) {
q.add(new Pair(node.right, diag));
}
}
ArrayList<Integer> sol = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : hash.entrySet()) {
sol.add(entry.getValue());
}
return sol;
}
}