Last active
October 26, 2018 20:26
-
-
Save jifalops/275d38e827bbaead27ff68f8e3f2c660 to your computer and use it in GitHub Desktop.
Random binary tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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