Skip to content

Instantly share code, notes, and snippets.

@zerobias
Created November 25, 2018 02:40
Show Gist options
  • Save zerobias/d5e1937040c1339c18b4e1b43ebbd613 to your computer and use it in GitHub Desktop.
Save zerobias/d5e1937040c1339c18b4e1b43ebbd613 to your computer and use it in GitHub Desktop.
class Tree {
constructor(root) {
this.root = null
this.root = root
}
buildFromLinks(links) {
const nodes = new Array(26)
const forest = new Array(26)
for (const link of links) {
const ends = link.split(' ')
const start =
(((c) => (c.charCodeAt == null ? c : c.charCodeAt(0)))(
ends[0].charAt(0),
) -
'a'.charCodeAt(0)) |
0
const end =
(((c) => (c.charCodeAt == null ? c : c.charCodeAt(0)))(
ends[1].charAt(0),
) -
'a'.charCodeAt(0)) |
0
if (nodes[start] == null) {
nodes[start] = new TreeNode(
String.fromCharCode(start + 'a'.charCodeAt(0)),
)
forest[start] = new Tree(nodes[start])
}
if (nodes[end] == null)
nodes[end] = new TreeNode(String.fromCharCode(end + 'a'.charCodeAt(0)))
else forest[end] = null
nodes[start].addChild(nodes[end], end)
}
return forest
}
static printForest(links) {
const t = new Tree(new TreeNode('\u0000'))
const array4676 = t.buildFromLinks(links)
for (const t1 of array4676) {
if (t1 != null) {
t1.root.printTreeIdented('')
console.info('')
}
}
}
static main(args) {
const links1 = ['a b', 'b c', 'b d', 'a e']
console.info('------------ Forest 1 ----------------')
Tree.printForest(links1)
const links2 = [
'a b',
'a g',
'b c',
'c d',
'd e',
'c f',
'z y',
'y x',
'x w',
]
console.info('------------ Forest 2 ----------------')
Tree.printForest(links2)
}
static get __class() {
return 'Tree'
}
}
class TreeNode {
constructor(c) {
this.children = null
this.c = null
this.c = c
this.children = new Array(26)
}
addChild(n, index) {
this.children[index] = n
}
printTreeIdented(indent) {
console.info(`${indent}-->${this.c}`)
for (const child of this.children) {
if (child != null) child.printTreeIdented(`${indent} |`)
}
}
static get __class() {
return 'TreeNode'
}
}
Tree.main(null)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment