Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding bottom view binary tree problem solution #130

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
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
  • Loading branch information
karimelazzouni committed Oct 23, 2019
commit 4fe5c166744a7de6ac77792c83c778876fef19af
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules/
coverage/
coverage/
.vs/
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,8 @@
"eslint-config-airbnb-base": "^13.1.0",
"eslint-plugin-import": "^2.14.0",
"jest": "^25.0.0"
},
"dependencies": {
"hashmap": "^2.4.0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,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();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should return an array instead of Iterator @karimelazzouni

};