-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
49 lines (38 loc) · 1.1 KB
/
Copy pathsolution.java
File metadata and controls
49 lines (38 loc) · 1.1 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
/* Structure of binary tree node
class Node{
public:
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
*/
class Solution {
// DFS traversal function
void dfs(Node root, int col, TreeMap<Integer, Integer> map) {
// If node is null, stop recursion
if (root == null)
return;
// Add node value into current vertical column
map.put(col, map.getOrDefault(col, 0) + root.data);
// Traverse left side
dfs(root.left, col - 1, map);
// Traverse right side
dfs(root.right, col + 1, map);
}
public ArrayList<Integer> verticalSum(Node root) {
// TreeMap keeps keys sorted automatically
TreeMap<Integer, Integer> map = new TreeMap<>();
// Start traversal from column 0
dfs(root, 0, map);
ArrayList<Integer> ans = new ArrayList<>();
// Store sums in sorted vertical order
for (int value : map.values()) {
ans.add(value);
}
return ans;
}
}