Skip to content

Commit 2323351

Browse files
authoredOct 24, 2019
Merge pull request #130 from karimelazzouni/karimelazzouni/bottom-view-binary-tree
Adding bottom view binary tree problem solution
2 parents 79e07ad + 5c42a96 commit 2323351

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed
 

‎.gitignore

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
node_modules/
2-
coverage/
2+
coverage/
3+
.vs/
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
const Queue = require('../../../Queue');
2+
3+
// Determines the bottom view of a binary tree
4+
// Takes a BinaryTree as a parameter
5+
// Returns an integer array
6+
// Time complexity: O(n) where n is the number of nodes in the tree
7+
8+
module.exports = function bottomView(binaryTree) {
9+
if (binaryTree == null || binaryTree.root == null) {
10+
return [];
11+
}
12+
13+
// root's horizontal distance = 0
14+
const horizontalDistance = 0;
15+
16+
// create a map to track most recent visited nodes per hd
17+
const hdToNodeValue = new Map();
18+
19+
// perform bfs
20+
const q = new Queue();
21+
q.enqueue([binaryTree.root, horizontalDistance]);
22+
23+
while (q.length() > 0) {
24+
const currentNodeTuple = q.dequeue();
25+
const currentNode = currentNodeTuple[0];
26+
const currentHd = currentNodeTuple[1];
27+
hdToNodeValue.set(currentHd, currentNode.value);
28+
29+
if (currentNode.leftChild != null && currentNode.leftChild.value != null) {
30+
q.enqueue([currentNode.leftChild, currentHd - 1]);
31+
}
32+
33+
if (currentNode.rightChild != null && currentNode.rightChild.value != null) {
34+
q.enqueue([currentNode.rightChild, currentHd + 1]);
35+
}
36+
}
37+
38+
return Array.from(hdToNodeValue.values());
39+
};

0 commit comments

Comments
 (0)