binary-trees Node.js #8 program
source code
/* The Computer Language Benchmarks Game
https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
contributed by Isaac Gouy
*/
class Tree {
constructor(left, right) {
this.left = left
this.right = right
}
static with(depth) {
return (depth == 0)
? new Tree(null, null)
: new Tree( Tree.with(depth-1), Tree.with(depth-1))
}
nodeCount() {
return (this.left === null)
? 1
: 1 + this.left.nodeCount() + this.right.nodeCount()
}
clear() {
if (this.left != null) {
this.left.clear()
this.left = null
this.right.clear()
this.right = null
}
}
}
function main(n) {
const minDepth = 4
const maxDepth = minDepth + 2 > n ? minDepth + 2 : n
const stretchDepth = maxDepth + 1
stretch(stretchDepth)
longLivedTree = Tree.with(maxDepth)
for (let depth = minDepth; depth <= maxDepth; depth += 2){
const iterations = 1 << (maxDepth - depth + minDepth)
let sum = 0;
for (let i = 1; i <= iterations; i++){
sum += count(depth)
}
console.log(`${iterations}\t trees of depth ` +
`${depth}\t check: ${sum}`)
}
console.log(`long lived tree of depth ` +
`${maxDepth}\t check: ${longLivedTree.nodeCount()}`)
}
function stretch(depth) {
console.log(`stretch tree of depth ` +
`${depth}\t check: ${count(depth)}`);
}
function count(depth) {
t = Tree.with(depth)
c = t.nodeCount()
t.clear()
return c
}
main( +process.argv.length > 2
? +process.argv[2]
: 7 )
notes, command-line, and program output
NOTES:
64-bit Ubuntu quad core
v23.0.0
Tue, 22 Oct 2024 22:40:11 GMT
MAKE:
cp -L binarytrees.node-8.node binarytrees.js
0.16s to complete and log all make actions
COMMAND LINE:
/opt/src/node-v23.0.0/bin/node binarytrees.js 21
PROGRAM OUTPUT:
stretch tree of depth 22 check: 8388607
2097152 trees of depth 4 check: 65011712
524288 trees of depth 6 check: 66584576
131072 trees of depth 8 check: 66977792
32768 trees of depth 10 check: 67076096
8192 trees of depth 12 check: 67100672
2048 trees of depth 14 check: 67106816
512 trees of depth 16 check: 67108352
128 trees of depth 18 check: 67108736
32 trees of depth 20 check: 67108832
long lived tree of depth 21 check: 4194303