-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbstree.js
More file actions
72 lines (63 loc) · 1.55 KB
/
bstree.js
File metadata and controls
72 lines (63 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const adopt = (exemplar) => (...fns) => {
let obj = Object.assign({}, exemplar)
fns.forEach(fn => { obj[fn.name] = fn(obj) })
return obj
}
const newTree = () => adopt({
val: null,
lft: null,
rgt: null
})(insert, traverse)
const insert = (tree) => (val) => {
if (tree.val === null) {
tree.val = val
tree.lft = newTree()
tree.rgt = newTree()
} else {
insert(val > tree.val ? tree.rgt : tree.lft)(val)
}
}
const traverse = (tree) => (fn, depth = 0, trail = [0]) => {
if (tree == null || tree.val === null) { return }
traverse(tree.lft)(fn, depth + 1, [...trail, -1])
fn(tree.val, depth, trail)
traverse(tree.rgt)(fn, depth + 1, [...trail, 1])
}
const figs = {
up: '┌─➤ ',
br: '│ ',
dn: '└─➤ ',
sp: ' '
}
const figPath = trail => {
let frags = []
for (let i = 1; i < trail.length - 1; i++) {
frags.push(trail[i] === trail[i + 1] ? figs.sp : figs.br)
}
if (trail[trail.length - 1] === -1) {
frags.push(figs.up)
}
if (trail[trail.length - 1] === 1) {
frags.push(figs.dn)
}
return frags.join('')
}
// todo move visulizers to another file
const chalk = require('chalk')
const indent = (fn = x => `${x}`) => (val, depth, trail) => {
let str = fn(val)
console.log(chalk.gray(figPath(trail)) + chalk.white.bold(str))
}
const demo = () => {
let a = newTree()
let inserts = [0, 4, 7, 9, 10, 8, 5, 1, -1, -4, -7, -9, -10, -8, -5, 11, 12, 13, 14, 17, 16, 15]
inserts.forEach(n => insert(a)(n))
a.traverse(indent())
}
module.exports = {
newTree,
insert,
traverse,
indent,
demo
}