# Data Structures and Algorithms (JavaScript)

[![Node.js CI](https://github.com/hackingthejsinterview/js-data-structures-algorithms/actions/workflows/node.js.yml/badge.svg)](https://github.com/hackingthejsinterview/js-data-structures-algorithms/actions/workflows/node.js.yml)

A set of utilities of data structures for doing leetcode problems.

## Installation

```sh
npm install -S @hackingthejsinterview/js-data-structures-algorithms
```

## Development

```sh
cd js-data-structures-algorithms/
npm link
```

```sh
cd js-leetcode-questions/
npm link @hackingthejsinterview/js-data-structures-algorithms
```

Happy coding!

## Data Structures

Here is a list of support data structures:

- [Linked Lists](#linked-lists)
- Trees
  - [Binary Search Trees](#binary-search-tree)
- Graph
  - Directed
  - Undirected

## API

### Linked Lists

```js
const {
  ListNode,
  insert,
  remove,
  search,
  print
} = require('@hackingthejsinterview/js-data-structures-algorithms').LinkedList

let headNode = new ListNode(0)

insert(headNode, 1)
insert(headNode, 5)
insert(headNode, 10)
insert(headNode, 3)
insert(headNode, 17)

remove(headNode, 10)
remove(headNode, 3)

print(headNode) // 1, 5, 17

console.log(search(17)) // true
```

### Binary Search Tree

```js
const {
  // helpers
  TreeNode,
  printTreeDirectory,
  printTreePretty,

  // operations
  find,
  findMax,
  findMin,
  height,
  insert,
  remove,

  // traversals
  bfsInOrder,
  dfsInOrder,
  dfsPostOrder,
  dfsPreOrder
} = require('@hackingthejsinterview/js-data-structures-algorithms').BinarySearchTree

const rootNode = new TreeNode(9)
const nodes = [4, 17, 3, 6, 5, 7, 22, 20]
nodes.forEach((node) => {
  insert(rootNode, node)
})

console.log(bfsInOrder(rootNode)) // [9, 4, 17, 3, 6, 22, 5, 7, 20]
console.log(dfsInOrder(rootNode)) // [3, 4, 5, 6, 7, 9, 17, 20, 22]
console.log(dfsPreOrder(rootNode)) // [9, 4, 3, 6, 5, 7, 17, 22, 20]
console.log(dfsPostOrder(rootNode)) // [3, 5, 7, 6, 4, 20, 22, 17, 9]

console.log(printTreeDirectory(rootNode))
/*
Output
------
9
├──4
│  ├──3
│  └──6
│     ├──5
│     └──7
└──17
    ├──10
    └──22
      ├──20

*/

console.log(printTreePretty(rootNode))
/*
Output
------
                 9
                / \
               /   \
              /     \
             /       \
            /         \
           /           \
          4            17
         / \           / \
        /   \         /   \
       /     \       /     \
      3       6     10     22
             / \           /
            /   \         /
           /     \       /
          5       7     20
*/
```
