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();
}
}
function main(n) {
const minDepth = 4
const maxDepth = minDepth + 2 > n ? minDepth + 2 : n
const stretchDepth = maxDepth + 1
let count = Tree.with(stretchDepth).nodeCount()
console.log(`stretch tree of depth ` +
`${stretchDepth}\t check: ${count}`);
longLivedTree = Tree.with(maxDepth)
for (let depth = minDepth; depth <= maxDepth; depth += 2){
const iterations = 1 << (maxDepth - depth + minDepth)
let count = 0;
for (let i = 1; i <= iterations; i++){
count += Tree.with(depth).nodeCount()
}
console.log(`${iterations}\t trees of depth ` +
`${depth}\t check: ${count}`)
}
console.log(`long lived tree of depth ` +
`${maxDepth}\t check: ${longLivedTree.nodeCount()}`)
}
main( +process.argv.length > 2
? +process.argv[2]
: 7 )
notes, command-line, and program output
NOTES:
64-bit Ubuntu quad core
v22.8.0
Tue, 01 Oct 2024 03:25:03 GMT
MAKE:
cp -L binarytrees.node-8.node binarytrees.js
0.06s to complete and log all make actions
COMMAND LINE:
/opt/src/node-v22.8.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