File tree 2 files changed +41
-1
lines changed
src/_DataStructures_/Trees/BinaryTree/bottom-view-binary-tree
2 files changed +41
-1
lines changed Original file line number Diff line number Diff line change 1
1
node_modules /
2
- coverage /
2
+ coverage /
3
+ .vs /
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments