Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2323351

Browse files
authored
Merge pull request knaxus#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‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
node_modules/
2-
coverage/
2+
coverage/
3+
.vs/
Lines changed: 39 additions & 0 deletions
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)

AltStyle によって変換されたページ (->オリジナル) /