/** * Binary search tree implementation in JavaScript. * Requires JS.Class - http://jsclass.jcoglan.com/ * * Performs naïve comparison using operators; a good extension would be support * for JS.Class's Comparable module. */ var BinaryTree = new JS.Class({ initialize: function(left, value, right) { this.value = value; this.left = left; this.right = right; }, isEmpty: function() { return !this.value; }, insert: function(x) { if (this.isEmpty()) { this.value = x; } else if (x < this.value) { (this.left) ? this.left.insert(x) : this.left = new BinaryTree(null, x, null); } else if (x > this.value) { (this.right) ? this.right.insert(x) : this.right = new BinaryTree(null, x, null); } }, isMember: function(x) { if (this.isEmpty()) { return false; } else if (x < this.value) { return !!this.left && this.left.isMember(x); } else if (x > this.value) { return !!this.right && this.right.isMember(x); } else { return true; } } });