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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
| class Node { constructor(value) { this.data = value this.leftChild = null this.rightChild = null } }
class BST { constructor() { this.root = null }
insert(value) { let node = new Node(value)
if (!this.root) { this.root = node return }
this._insertNode(this.root, node) }
min() { return this._findMin(this.root) }
_findMin(node) { if (!node) return null
while (node.leftChild) node = node.leftChild
return node }
max() { return this._findMax(this.root) }
_findMax(node) { if (!node) return null
while (node.rightChild) node = node.rightChild
return node }
remove(data) { this.root = this._remove(this.root, data) }
_remove(node, key) { if (!node) return null
if (key < node.data) { node.leftChild = this._remove(node.leftChild, key) return node } else if (key > node.data) { node.rightChild = this._remove(node.rightChild, key) return node } else { if (node.leftChild === null && node.rightChild === null) { node = null return node } else if (node.rightChild === null) { node = node.leftChild return node } else if (node.leftChild === null) { node = node.rightChild return node }
let min = this._findMin(node.rightChild) node.data = min.data node.rightChild = this._remove(node.rightChild, min.data)
return node } }
_insertNode(node, newNode) { if (newNode.data < node.data) { if (node.leftChild === null) node.leftChild = newNode else this._insertNode(node.leftChild, newNode) } else { if (node.rightChild === null) node.rightChild = newNode else this._insertNode(node.rightChild, newNode) } }
preOrderTraverseTree() { this._preOrderTraverse(this.root) }
_preOrderTraverse(node) { if (node) { console.log(node.data) this._preOrderTraverse(node.leftChild) this._preOrderTraverse(node.rightChild) } }
inOrderTraverseTree() { this._inOrderTraverse(this.root) }
_inOrderTraverse(node) { if (node) { this._inOrderTraverse(node.leftChild) console.log(node.data) this._inOrderTraverse(node.rightChild) } }
postOrderTraverseTree() { this._postOrderTraverse(this.root) }
_postOrderTraverse(node) { if (node) { this._postOrderTraverse(node.leftChild) this._postOrderTraverse(node.rightChild) console.log(node.data) } } }
let bst = new BST() bst.insert(2) bst.insert(3) bst.insert(1) bst.insert(-1) bst.insert(5) bst.insert(-2)
bst.inOrderTraverseTree()
console.log(bst.min()) console.log(bst.max())
bst.remove(2) bst.inOrderTraverseTree()
|