diff --git a/.gitignore b/.gitignore index 642271f5..6d438035 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ node_modules/ -coverage/ \ No newline at end of file +coverage/ +.vs/ \ No newline at end of file diff --git a/src/_DataStructures_/Trees/BinaryTree/bottom-view-binary-tree/index.js b/src/_DataStructures_/Trees/BinaryTree/bottom-view-binary-tree/index.js new file mode 100644 index 00000000..e634fdc0 --- /dev/null +++ b/src/_DataStructures_/Trees/BinaryTree/bottom-view-binary-tree/index.js @@ -0,0 +1,39 @@ +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 Map(); + + // 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 Array.from(hdToNodeValue.values()); +};