Skip to content

Language Shootout

A user-supported site Fastest, Shortest, Simplest

Binary Trees

C++ g++ #1 — Binary Trees

Allocate, walk and deallocate many perfect binary trees, while one long-lived tree stays alive throughout.

Time 8,000.8 ms
CPU time 7,974.8 ms
Peak memory 265,700 KB
gz 539 bytes — comments removed, gzipped
Style ★★★★☆
Implementation C++ — C++ (GCC) 15.2
By sysop-
Submitted September 24, 2026

Style assessment

This is essentially the canonical Benchmarks Game C++ entry: RAII via a recursive ~Node destructor, std::max, iostream output, and clean recursion in make/check are all idiomatic and the code is admirably simple. Minor deductions for the unused <stdio.h> include, terse names like l/r/c, slightly inconsistent tab/space indentation, and the fact that faster C++ entries typically add an arena/pool allocator; dropping the dead include and using <cstdlib> would polish it.

/* The Computer Language Benchmarks Game 
 * http://benchmarksgame.alioth.debian.org/
 *
 * Contributed by Jon Harrop
 * Modified by Alex Mizrahi
 *  *reset*
 */

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

struct Node {
  Node *l, *r;
  Node() : l(0), r(0) {}
  Node(Node *l2, Node *r2) : l(l2), r(r2) {}
  ~Node() { delete l; delete r; }
  int check() const {
	  if (l)
		return l->check() + 1 + r->check(); 
	  else return 1;
  }
};

Node *make(int d) {
  if (d == 0) return new Node();
  return new Node(make(d-1), make(d-1));
}

int main(int argc, char *argv[]) {
  int min_depth = 4,
    max_depth = std::max(min_depth+2,
			 (argc == 2 ? atoi(argv[1]) : 10)),
    stretch_depth = max_depth+1;

  {
    Node *c = make(stretch_depth);
    std::cout << "stretch tree of depth " << stretch_depth << "\t "
      << "check: " << c->check() << std::endl;
    delete c;
  }

  Node *long_lived_tree=make(max_depth);

  for (int d=min_depth; d<=max_depth; d+=2) {
    int iterations = 1 << (max_depth - d + min_depth), c=0;
    for (int i=1; i<=iterations; ++i) {
      Node *a = make(d);
      c += a->check();
      delete a;
    }
    std::cout << iterations << "\t trees of depth " << d << "\t "
	      << "check: " << c << std::endl;
  }

  std::cout << "long lived tree of depth " << max_depth << "\t "
	    << "check: " << (long_lived_tree->check()) << "\n";

  delete long_lived_tree;

  return 0;
}

Back to Binary Trees