ionfish (owner)

Revisions

gist: 129476 Download_button fork
public
Description:
Binary search tree implementation in JavaScript.
Public Clone URL: git://gist.github.com/129476.git
Embed All Files: show embed
binary_tree.js #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* 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;
    }
  }
});