|
| 1 | +function RedBlackTree() { |
| 2 | + |
| 3 | + var Colors = { |
| 4 | + RED: 0, |
| 5 | + BLACK: 1 |
| 6 | + }; |
| 7 | + |
| 8 | + var Node = function (key, color) { |
| 9 | + this.key = key; |
| 10 | + this.left = null; |
| 11 | + this.right = null; |
| 12 | + this.color = color; |
| 13 | + |
| 14 | + this.flipColor = function(){ |
| 15 | + if (this.color === Colors.RED) { |
| 16 | + this.color = Colors.BLACK; |
| 17 | + } else { |
| 18 | + this.color = Colors.RED; |
| 19 | + } |
| 20 | + }; |
| 21 | + }; |
| 22 | + |
| 23 | + var root = null; |
| 24 | + |
| 25 | + this.getRoot = function () { |
| 26 | + return root; |
| 27 | + }; |
| 28 | + |
| 29 | + var isRed = function(node){ |
| 30 | + if (!node){ |
| 31 | + return false; |
| 32 | + } |
| 33 | + return node.color === Colors.RED; |
| 34 | + }; |
| 35 | + |
| 36 | + var flipColors = function(node){ |
| 37 | + node.left.flipColor(); |
| 38 | + node.right.flipColor(); |
| 39 | + }; |
| 40 | + |
| 41 | + var rotateLeft = function(node){ |
| 42 | + var temp = node.right; |
| 43 | + if (temp !== null) { |
| 44 | + node.right = temp.left; |
| 45 | + temp.left = node; |
| 46 | + temp.color = node.color; |
| 47 | + node.color = Colors.RED; |
| 48 | + } |
| 49 | + return temp; |
| 50 | + }; |
| 51 | + |
| 52 | + var rotateRight = function (node) { |
| 53 | + var temp = node.left; |
| 54 | + if (temp !== null) { |
| 55 | + node.left = temp.right; |
| 56 | + temp.right = node; |
| 57 | + temp.color = node.color; |
| 58 | + node.color = Colors.RED; |
| 59 | + } |
| 60 | + return temp; |
| 61 | + }; |
| 62 | + |
| 63 | + var insertNode = function(node, element) { |
| 64 | + |
| 65 | + if (node === null) { |
| 66 | + return new Node(element, Colors.RED); |
| 67 | + } |
| 68 | + |
| 69 | + var newRoot = node; |
| 70 | + |
| 71 | + if (element < node.key) { |
| 72 | + |
| 73 | + node.left = insertNode(node.left, element); |
| 74 | + |
| 75 | + } else if (element > node.key) { |
| 76 | + |
| 77 | + node.right = insertNode(node.right, element); |
| 78 | + |
| 79 | + } else { |
| 80 | + node.key = element; |
| 81 | + } |
| 82 | + |
| 83 | + if (isRed(node.right) && !isRed(node.left)) { |
| 84 | + newRoot = rotateLeft(node); |
| 85 | + } |
| 86 | + |
| 87 | + if (isRed(node.left) && isRed(node.left.left)) { |
| 88 | + newRoot = rotateRight(node); |
| 89 | + } |
| 90 | + if (isRed(node.left) && isRed(node.right)) { |
| 91 | + flipColors(node); |
| 92 | + } |
| 93 | + |
| 94 | + return newRoot; |
| 95 | + }; |
| 96 | + |
| 97 | + this.insert = function(element) { |
| 98 | + root = insertNode(root, element); |
| 99 | + root.color = Colors.BLACK; |
| 100 | + }; |
| 101 | +} |
0 commit comments