Skip to content

Commit 4fe5c16

Browse files
Adding bottom view binary tree problem solution
- Solution based on https://www.geeksforgeeks.org/bottom-view-binary-tree/ - Modified `.gitignore` to ignore Visual Studio's files
1 parent 43ed1bc commit 4fe5c16

File tree

4 files changed

+50
-1
lines changed

4 files changed

+50
-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/

package-lock.json

+5
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

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

0 commit comments

Comments
 (0)