-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0314-binary-tree-vertical-order-traversal.js
More file actions
50 lines (43 loc) · 1.57 KB
/
0314-binary-tree-vertical-order-traversal.js
File metadata and controls
50 lines (43 loc) · 1.57 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
/**
* Binary Tree Vertical Order Traversal
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var verticalOrder = function (root) {
if (!root) {
return [];
}
const columnValuesMap = new Map();
const bfsQueue = [[root, 0]];
let minColumnIndex = 0;
let maxColumnIndex = 0;
while (bfsQueue.length > 0) {
const currentTuple = bfsQueue.shift();
const currentNode = currentTuple[0];
const currentColumn = currentTuple[1];
const nodeValue = currentNode.val;
if (!columnValuesMap.has(currentColumn)) {
columnValuesMap.set(currentColumn, []);
}
columnValuesMap.get(currentColumn).push(nodeValue);
if (currentNode.left) {
const leftChildColumn = currentColumn - 1;
const leftChildTuple = [currentNode.left, leftChildColumn];
bfsQueue.push(leftChildTuple);
minColumnIndex = Math.min(minColumnIndex, leftChildColumn);
}
if (currentNode.right) {
const rightChildColumn = currentColumn + 1;
const rightChildTuple = [currentNode.right, rightChildColumn];
bfsQueue.push(rightChildTuple);
maxColumnIndex = Math.max(maxColumnIndex, rightChildColumn);
}
}
const finalResultArray = [];
for (let columnIndexIterator = minColumnIndex; columnIndexIterator <= maxColumnIndex; columnIndexIterator++) {
if (columnValuesMap.has(columnIndexIterator)) {
finalResultArray.push(columnValuesMap.get(columnIndexIterator));
}
}
return finalResultArray;
};