forked from knaxus/problem-solving-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
40 lines (31 loc) · 1.16 KB
/
index.js
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
const HashMap = require('hashmap');
const Queue = require('../../../Queue');
// Determines the bottom view of a binary tree
// Takes a BinaryTree as a parameter
// Returns an integer array
// Time complexity: O(n) where n is the number of nodes in the tree
module.exports = function bottomView(binaryTree) {
if (binaryTree == null || binaryTree.root == null) {
return [];
}
// root's horizontal distance = 0
const horizontalDistance = 0;
// create a map to track most recent visited nodes per hd
const hdToNodeValue = new HashMap();
// perform bfs
const q = new Queue();
q.enqueue([binaryTree.root, horizontalDistance]);
while (q.length() > 0) {
const currentNodeTuple = q.dequeue();
const currentNode = currentNodeTuple[0];
const currentHd = currentNodeTuple[1];
hdToNodeValue.set(currentHd, currentNode.value);
if (currentNode.leftChild != null && currentNode.leftChild.value != null) {
q.enqueue([currentNode.leftChild, currentHd - 1]);
}
if (currentNode.rightChild != null && currentNode.rightChild.value != null) {
q.enqueue([currentNode.rightChild, currentHd + 1]);
}
}
return hdToNodeValue.values();
};