Skip to content

Instantly share code, notes, and snippets.

@jifalops
Last active October 26, 2018 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jifalops/275d38e827bbaead27ff68f8e3f2c660 to your computer and use it in GitHub Desktop.
Save jifalops/275d38e827bbaead27ff68f8e3f2c660 to your computer and use it in GitHub Desktop.
Random binary tree
import 'dart:math';
const maxNodes = 10;
void main() {
final rng = Random();
final nodes = List.generate(maxNodes, (index) => Node(index + 1));
final openNodes = [nodes[0]];
nodes.skip(1).forEach((node) {
node.parent = openNodes[rng.nextInt(openNodes.length)];
openNodes.add(node);
if (node.parent.right != null ||
(node.parent.left == null && rng.nextBool()))
node.parent.left = node;
else
node.parent.right = node;
if (!node.parent.isOpen) openNodes.remove(node.parent);
});
nodes.forEach(print);
}
class Node {
Node(this.id);
final int id;
Node parent;
Node left;
Node right;
bool get isOpen => left == null || right == null;
@override
String toString() => '$id: (${left?.id ?? '_'}, ${right?.id ?? '_'})';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment